c language and ds main
TRANSCRIPT
-
8/4/2019 C Language and DS Main
1/62
C Language:
1) Difference between Technology and Language.
2) Background process in C
3) Structure of C program
Include header section
Global declaration section
main() function name
{
Declaration part
Executable part
}
Userdefined functions
{
}
-
8/4/2019 C Language and DS Main
2/62
Note: C also known as free form language.
Ex: a=b+c; d=b*c;
4) C Tokens:
Keywords: static, int, void
Identifiers: deposit,amount
Constants:20,23.4
Strings: xyz
Special Symbols: (),{}
Operators:+,-,*
Identifiers: Names for functions, variables, arrays or user defined types.
Constants:
1) Numeric constants : Integer constants(10,-20), Real constants(5.23)
2) Character constants: single character constant(a), string constants(abc)
Data types:
a) Integer
SignedType: int, short int, long int
UnsignedType: unsigned int, unsigned short int, unsigned long int
-
8/4/2019 C Language and DS Main
3/62
b) Character: signed char, unsigned char
b) Floating point
float, double, long double
Data type size(bytes) Range format string
Char 1 -128 to 127 %c
Unsigned char 1 0 to 255 %c
Short or int 2 -32,768 to 32,767 %i or %d
Unsigned int 2 0 to 65535 %u
long 4 -2147483648 to 2147483647 %ld
unsigned long 4 0 to 4294967295 %lu
float 4 3.4 e-38 to 3.4e+38 %f or %g
double 8 1.7e-308 to 1.7e+308 %lf
long double 10 3.4e-4932 to 1.1e+4932 %lf
-
8/4/2019 C Language and DS Main
4/62
Variables: name given to a memory location during storage of data ie variable is a data
name used for storing a data value.
Rules:-
Variable name should not use c keywords.
Variable name should not start with digit.
Scope and life time of a variable: Example
Questions on DataTypes and Variables:
1)#include
void main(){
double num=5.2;
int var=5;
printf("%d\t",sizeof(!num));
printf("%d\t",sizeof(var=15/2));
printf("%d",var);
}
2. #include
int main(){
int goto=5;
printf("%d",goto);
return 0;
}
-
8/4/2019 C Language and DS Main
5/62
3.#include
int main(){
long int 1a=5l;
printf("%ld",1a);
return 0;
}
4.#include
int main(){
int _=5;
int __=10;
int ___;
___=_+__;
printf("%i",___);
return 0;
}
5.#inlcude
Static num =5;
Int num;
-
8/4/2019 C Language and DS Main
6/62
Void main()
{
Printf(%d,num);
}
6.#inlcude
Static num =5;
Int num=5;
Void main()
{
Printf(%d,num);
}
1Ans: 2,2,5
2Ans: Compilation Error
3Ans: Compilation
4Ans: 15
5Ans: 5
6Ans: compilation error. Variable initialized more than once
Operators :
1) Arithmetic Operators : +,-,*,/ and %]
-
8/4/2019 C Language and DS Main
7/62
2) Relational Operators : >,=,>, . left to right! ~ ++ -- + - * (type) sizeofright to left* / % left to right+ - left to right> left to right< >= left to right== != left to right& left to right^ left to right| left to right
&& left to right|| left to right?: right to left= += -= *= /= %= &= ^= |= = right to left, left to right
Questions on Operators:
-
8/4/2019 C Language and DS Main
8/62
1)What will be output of the following program?
#include
int main(){
int i=1;
i=2+2*i++;
printf("%d",i);
return 0;
}
2)What will be output of the following program?
#include
int main(){
int i=0;
int x=++i+i++-i++;
printf("%d",x);
printf("%d",i);
return 0;
}
3. What will be output of the following program?
-
8/4/2019 C Language and DS Main
9/62
#include
int main(){
int x=100,y=20,z=5;
printf("%d %d %d");
return 0;}
Output: 5 20 100
4. #define square(X) X*X;
void main()
{
int i;
i=64/square(4);
printf( %d,i);}
5.. void main()
{
int x;
x=3+4-7*8/5%10;
printf("x=%d",x);
}
1Ans: 5
2Ans:0,3
3Ans: 5 20 100
4Ans: 64
5Ans:6
Control Structures:
1) Branching or Decision making statements:
-
8/4/2019 C Language and DS Main
10/62
If, If-else, nested if, switch
2) Iterative or looping statements :
For, while, do- while
Questions on Control structures:
1.What will be output when you will execute following c code?
#include
void main(){
int a=100;
if(a>10)
printf("M.S. Dhoni");
else if(a>20)
printf("M.E.K Hussey");
else if(a>30)
printf("A.B. de villiers");
}
2. What will be output when you will execute following c code?
#include
void main(){
int x=-1,y=-1;
if(++x=++y)
printf("R.T. Ponting");
else
printf("C.H. Gayle");
}
-
8/4/2019 C Language and DS Main
11/62
3. What will be output when you will execute following c code?
#include
void main(){if(sizeof(void))
printf("M. Muralilidaran");
else
printf("Harbhajan Singh");
}
4.What will be output when you will execute following c code?
#include
void main(){
int m=5,n=10,q=20;if(q/n*m)
printf("William Gates");
else
printf(" Warren Buffet");
printf(" Carlos Slim Helu");
}
5. What will be output when you will execute following c
code?
#include
void main(){
int a=5,b=10;
if(++a||++b)
printf("%d %d",a,b);
else
printf("John Terry");
}
-
8/4/2019 C Language and DS Main
12/62
6. What will be output when you will execute following c
code?#include
void main(){int check=2;
switch(check){
case 1: printf("D.W.Steyn");
case 2: printf(" M.G.Johnson");
case 3: printf(" Mohammad Asif");
default: printf(" M.Muralidaran");
}
}
7.What will be output when you will execute following c code?
#include
void main(){
int movie=1;
switch(movie
-
8/4/2019 C Language and DS Main
13/62
9. What will be output of following c code?
#include
int main(){
int i,j;
i=j=2,3;
while(--i&&j++)
printf("%d %d",i,j);
return 0;
}
10.#include
int main(){
static int i;
for(++i;++i;++i) {
printf("%d ",i);
if(i==4) break;
}
return 0;
}
-
8/4/2019 C Language and DS Main
14/62
1Ans: M.S. Dhoni
2Ans: Compilation error
3Ans: Compilation error
4Ans: William Gates Carlos Slim Helu
5Ans: 6,10
6Ans: M.G.Johnson Mohammad Asif M.Muralidaran
7Ans: Race
8Ans:1
9Ans:1,3 (with warning during compilation )
10Ans:2,4 ( static variableb init to 0)
Pointers: & (reference operator), * (dereference)
Arrays:
1)Single dimensional array
Ex: int a[10];
2)Two or multidimensional array
Ex: int a[2][2] , int a[2][2][2]
-
8/4/2019 C Language and DS Main
15/62
Questions on pointers,Arrays,:
1) main()
{
Int a=10,*b;
b=&a;
*b=*b+5;
Printf(%d,a);
}
2) main()
{
Int a=10,b=20,*x,*y,*t;
x=&a;
y=&b;
t=x;
x=y;
y=t;
Printf(%d %d,a,b);
Printf(\n %d %d,*x,*y);
}
-
8/4/2019 C Language and DS Main
16/62
3)main()
{
Int a=10,b=20,*x,*y,t;
x=&a;
y=&b;
t=*x;
*x=*y;
*y=t;
Printf(%d %d,a,b);
Printf(\n %d %d,*x,*y);
}
4)#include
int main(){
int *i,*j;
int x=10,y=20;
i=&x;
j=&y;
*i=*i+*j;
y=x+*j;
printf("x=%d y=%d",x,y);
}
-
8/4/2019 C Language and DS Main
17/62
5.#include
int main(){
int *i,*j;
int x=10,y=20;
i=&x;
j=&y;
*i=*i+*j+--*j;
y=x+*j+++x;
printf("x=%d y=%d",x,y);
}
6. #include
int main(){
char *cptr,c;
void *vptr,v;
c=10,v=0;
cptr=&c;
vptr=&v;
printf("%c %v",c,v);
}
-
8/4/2019 C Language and DS Main
18/62
7. #include
int main(){
int const *ptr=5;
printf("%d",++(*p));
}
8. #include
int main(){
char s[]=man;
for(int i=0;s[i];i++)
{
printf("\n %c %c %c %c",s[i],*(s+i),*(i+s),i[s]);
}
}
9. .#include
int main(){
char *p;
p=Hello;
printf(%c \n,*&*p);
}
-
8/4/2019 C Language and DS Main
19/62
10. main()
{
Int *p,x[]={2,4,6,8,10};
P=&x[10] ; //x;
Printf(%d,*p);
P=p+3;
Printf(%d,*p);
}
1Ans:15
2Ans: 10 20
20 10
3Ans: 20 10
20 10
4Ans: x=30 y=50
5Ans: x=49 y=117
6Ans: Compilation error
7Ans: compilation error, cannot increment constant pointer
8Ans: mmmm,aaaa,nnnn
9Ans: H
10Ans: 2 8
-
8/4/2019 C Language and DS Main
20/62
Q)prg to print even and odd nos from 1 to 10 .store the display results in
two separate arrays.
Void main()
{
Int sumo=0;sume=0,i=o,odd[5],even[5],a=-1,b=-1;
For(i=1;i
-
8/4/2019 C Language and DS Main
21/62
Q)Write a program to print string in reverse order without using string
reverse function.
Main()
{
Static char s[15];
Int I;
puts(enter a string);
gets(s);
puts(reverse string);
for(i=14;i>0;i--)
{
Printf(%c,s[i]);
}
}
Q) prg to detect the occurrence of a character in a given string
-
8/4/2019 C Language and DS Main
22/62
Main()
{
Static char s[15];
Char f;
Int I,l=0;
puts(enter a string);
gets(s);
puts(enter a character to find :);
f=getchar();
for(i=0;i
-
8/4/2019 C Language and DS Main
23/62
1.Main()
{
Int x[]={2,4,6,8,10};
Void abc(int *);
abc(x);
}
Void abc(int *p)
{
Int k;
For(k=0;k
-
8/4/2019 C Language and DS Main
24/62
x=*m;
*m=*n;
*n=x;
Printf(%d %d,*m,*n);
}
)
3.void main()
{
Int a=10,b=20;
Int *x,*y;
*x=*x*y;
*y=*x-*y;
*x=*x-*y;
Printf(%d %d,a,b);
Printf(%d %d,*x,*y);
}
2 Ans:2,4,6,8,10
2 Ans:20 10
10 20
-
8/4/2019 C Language and DS Main
25/62
3Ans: 20 10
20 10
String Functions:
i) In c language the group of characters ,digits, symbols enclosed
within quotation marks are called as string.
ii) Every string is terminated with null or \0 character.
iii) Strings are nothing but character arrays. Each character of a
string occupies 1 byte of memory .
String Operations:
the string functions strlen, strcpy, strcat, and strcmp, found
in .
strcat(s,t) : concatenate t to end of s
strncat(s,t,n) : concatenate n characters of t to end of s
strcmp(s,t) : return negative, zero, or positive for s < t, s == t, s > t
strncmp(s,t,n) : same as strcmp but only in first n charactersstrcpy(s,t) : copy t to s
strncpy(s,t,n) : copy at most n characters of t to s
strlen(s) : return length of s
strchr(s,c) : return pointer to first c in s, or NULL if not present
strstr(s1,s2) : checks for string in other string, or NULL if not present
strupr(s) converts lower case characters to a string of uppercase
strlwr(s) converts upper case characters to a string of lowercase
strrev(s) reverses all characters of a string.
Note: gets(stringvar or arrayvar)acts like scanf
Puts(stringname or arrayname)---acts like printf
-
8/4/2019 C Language and DS Main
26/62
Q)Prg: to compare two strings using gets and puts and strcmp method
Main()
{
Char sr1[10],sr2[10];
Int diff;
Printf(enter string1:);
gets(sr1);
printf(enter string2);
gets(sr2);
diff=strcmp(sr1,sr2);
if(diff==0)
puts(two strings are identical);else
puts(two strings are Different);
}
Q) prg to delete all the occurrences of vowels in a given string.
Void main()
{
Char line1[80],line2[80];
-
8/4/2019 C Language and DS Main
27/62
Int I,j=0;
Printf(enter text below);
gets(line1);
for(i=0;i
-
8/4/2019 C Language and DS Main
28/62
Char text[15];
Puts(enter string);
gets(text);
puts(reverse string);
puts(strrev(text));
}
Q)prg to check whether entered string is palindrome or not.
Main()
{
Char *string1;
Char *string2;
Printf(enter a string \n);
Scanf(%s,string1);
//copy original string1 to string2
String2=strdup(string1);
//reverse original string
String1=strrev(string1);
//compare string1,string2
If(strcmp(string1,string2)
Printf(\n %s is not a palindrome,string2);
Else
Printf(\n %s s palindrome ,string2);
}
-
8/4/2019 C Language and DS Main
29/62
Note: i) Difference between strdup and strcpy.
ii) int const *p;
const int *P;
Files:
i) File is a collection of numbers , symbols and text
placed on the disk.
ii) File can be read and modified as per the user
requirement.
-
8/4/2019 C Language and DS Main
30/62
iii) Files allow us to store information permanently on
the disk.
File Functions:
1)fopen() : creates a new file for read/write operation
2)fclose(): closes a file associated with file pointer.
3)closeall() : close all open files.
4)fgetc(): reads the character from current pointer
position and advances the pointer to next character.
5)getc(): acts like fgetc()
6) fprintc() : writes all types of data values to the
file
7)fscanf(): reads all types of data values from a file.
8)putc(): writes character by character to a file
9) fputc() : acts like putc().10) gets() : reads string from the file.
11) puts(): writes string to the file.
12) putw(): writes an integer to the file
13) getw(): reads an integer to the file
14) fread(): reads structure data written by fwrite()
function.
15) fwrite() : writes block of structured data to the
file.
16) fseek(): gets the pointer position anywhere in the
file.
-
8/4/2019 C Language and DS Main
31/62
17) feof() : detechs the end of file.
18) ftell() : returns the current pointer position.
19) rewind() : sets the record pointer at the beginning
of the
file.
20) unlink() : removes the specified file from the disk.
21) rename(): changes the name of the file.
Different modes of files:
a)Text modes b) Binary modes
Text modes:
1)w(write): this mode opens a new file on the disk for
writing.
Syn: fp=fopen(data.txt,w);
2) r(read): this modes open a pre-existing file forreading. (check for null pointer value using if
function)
Syn: fp= fopen(data.txt,r);
3)a(append): This mode opens a pre-existing file for
appending data.
4) w+(write+read): In this mode file can be written
and read.
5)a+(append+read): In this mode file can be read
and appended at the end.
-
8/4/2019 C Language and DS Main
32/62
6) r+(read+write): we can both read and write. If
the file doesnt exists ,the compiler returns null to the
pointer.
B) Binary Modes:
1) wb(write): this mode opens a binary file in write
mode.
Ex: fp=fopen(data.dat , wb );
Here data.dat file is opened in binary mode for
writing.
2)rb (read ) : this mode opens binary file in read
mode.
Ex:fp=fopen(data.dat,rb);
ex5
3)ab(append): this mode opens a binary file in append
mode.
Ex:fp=fopen(data.dat,ab);
4)r+b(read + write):this mode open pre-existing file
in read and write mode.
Ex:fp=fopen(data.dat,r+b);
5)w+b (read+write):this mode creates a new file in
read and write .
Ex:fp=fopen(data.dat,w+b);
6)a+b(append+read):this mode opens a file in append
mode.
http://opt/scribd/conversion/tmp/scratch9319/prg5.docxhttp://opt/scribd/conversion/tmp/scratch9319/prg5.docx -
8/4/2019 C Language and DS Main
33/62
Ex:fp=fopen(data.dat,a+b);
Q)prg Reading A File
#include "/sys/stdio.h"
main( )
{
FILE *funny;
int c;
funny = fopen("TENLINES.TXT","r");
if (funny == NULL) printf("File doesnt exist\n");
else {
do {
c = getc(funny); /* get one character from the file */
putchar(c); /* display it on the monitor */} while (c != EOF); /* repeat until EOF (end of file) */
}
fclose(funny);
}
Q)Prg Reading A Word At A Time
#include "/sys/stdio.h"main( )
{
FILE *fp1;
char oneword[100];
int c;
fp1 = fopen("TENLINES.TXT","r");
-
8/4/2019 C Language and DS Main
34/62
do {
c = fscanf(fp1,"%s",oneword); /* got one word from the file */
printf("%s\n",oneword); /* display it on the monitor */
} while (c != EOF); /* repeat until EOF */
fclose(fp1);
}
Copying one File to other
#include "/sys/stdio.h"main( )
{
FILE *funny,*printer;
int c;
funny = fopen("TENLINES.TXT","r"); /* open input file */
printer = fopen("PRN","w"); /* open printer file */
do {
c = getc(funny); /* got one character from the file */
if (c != EOF) {
putchar(c); /* display it on the monitor */putc(c,printer); /* print the character */
}
} while (c != EOF); /* repeat until EOF (end of file) */
fclose(funny);
fclose(printer);
}
-
8/4/2019 C Language and DS Main
35/62
Structures and Unions:
i) structure is a user defined data type ,which consists of different data types
members. Its reserves contiguous memory. Unlike array , which consists of
similar data elements.
ii) structure declaration wont allocate any memory. Once an variable for a
structure is defined memory will be allocated.
iii)memory allocates for structure will the sum of memory reserved for
structure members. Iv) union is almost like structure but the difference is all
the members of unions will not be allocated memory at once. Memory will be
allocated one after the other upon the usage. Memory allocated for the union
will be equal to the memory for its highest datatype member.
iv) we can have structure within structure that is we can have nested structure.
Structure prg:
Struct student
{
int rno;
string name;
-
8/4/2019 C Language and DS Main
36/62
};
Void main()
{
struct Student s;
Printf(\n enter rno ,s.name );
Scanf(%d,&s.carno);
Scanf(%d %d %d,&s->name);
Printf(\n student details are );
Printf(\n %d \t ,s->no);
printf(%d ,s->name);
}
Pointer to structure prg:
Struct student
{
int rno;
string name;
};
Void main()
{
struct Student s,*sptr;
sptr=&s;
-
8/4/2019 C Language and DS Main
37/62
Printf(\n enter rno ,s->name );
Scanf(%d,&s->carno);
Scanf(%d %d %d,&s.name);
Printf(\n student details are );
Printf(\n %d \t ,s->no);
printf(%d ,s->name);
}
Q) prg to illustrate nested structure
Void main()
{
Struct time
{
int second;
int minute;
int hour;
};
Struct t
{
int carno;
struct time st;
struct time rt;
};
-
8/4/2019 C Language and DS Main
38/62
Struct t r1;
Printf(\n carno startingtime reaching time );
Scanf(%d,&r1.carno);
Scanf(%d %d %d,&r1.st.hour,&r1.st.minute,&r1.st.second);
Scanf(%d %d %d,&r1.rt.hour,&r1.rt.minute,&r1.rt.second);
Printf(\n carno startingtime reaching time );
Printf(\n %d \t ,r1.carno);
printf(%d %d %d,&r1.st.hour,&r1.st.minute,&r1.st.second);
printf(%d %d %d,&r1.rt.hour,&r1.rt.minute,&r1.rt.second);
}
Array of Structures:
Q) prg to illustrate array of structures.
Void main()
{
int k;
Struct time
{
int second;
int minute;
int hour;
};
Struct t
-
8/4/2019 C Language and DS Main
39/62
{
int carno;
struct time st;
struct time rt;
};
Struct t r1[3]; //declaring array of structures.
Printf(\n carno startingtime reaching time );
For(k=0;k
-
8/4/2019 C Language and DS Main
40/62
Dyanamic memory allocation methods:
1) Malloc: allocate a block of memory.
Used for primitive data types.
Syn:ptr =(type*) malloc(size);
Ex: x= (int*) malloc(100*sizeof(int));
Ex: cptr=(char*) malloc(10);
2) Calloc: allocates multiple blocks of memory.
Used for user defined data types like structure.
Syn: ptr= (type *) calloc(n,size);
Ex: struct student
{
-
8/4/2019 C Language and DS Main
41/62
Char name[250];
Float age;
}
typedef struct student
record *sptr;
sptr=(record*) calloc(5,sizeof(student));
Data Structures:
i)Its a collection of organized data that are
related to each other.Data structures can be
classified into two types
a) linear data structure ex: array,stack,queque,circular queue,list
b) Non-Linear data structure ex:trees and graphs
stack:
i) Its a linear data structure in whichinsertion and deletion will be at one end. I
-
8/4/2019 C Language and DS Main
42/62
ii) It follows LIFO(last in first out) order.
iii)Consists of push( for insertion) and pop(for
deletion).
iv) Uses single pointer (top) for insertion anddeletion.
v) Example pile of books or plates in
restaurant.
vi) It can be implemented using array,lists.
Queue:
i) Its also linear data structure, in which
insertion will be done at rare end and
deletion, will be done at front end.
ii) Its follows FIFO (first in first out) order.
iii)Consists of insert , delete options
iv) Uses two pointer rare and front.
v) Example railway ticket reservation.
vi) It can be implemented using array,lists.
Stack:
50
30
20
-
8/4/2019 C Language and DS Main
43/62
3
top=2
1
0
Queue:
Front rare
Circular Queue:
i) Queue as circular known as Circular queue.
ii) Instead of taking linear approach, circular queue takes a
circular approach.
iii)
10 20 30 12
2
-
8/4/2019 C Language and DS Main
44/62
Linked Lists:
i) List using array ,has the problem in which the size of the array
must be specified precisely at the beginning.
ii) A linked lists is a collection of data segments each data segment
is a structure , which consists of data or field and link or
pointer to next data segment.
iii) Its a dynamic data structure. Therefore, the primaryadvantage of linked lists over arrays is that linked lists can
grow or shrink in size during the execution of a program.
iv) It does not waste memory space, it uses the memory that is
needed for the list at any point of time. Because its not
necessary to specify the no.of nodes in the list.
Types of Linked lists:
a) Linear list
10 12 3
10 12 3 0
-
8/4/2019 C Language and DS Main
45/62
b) Circular List
c) Single Linked list:
d) double Linked list:
10 12 3
10 12 3 0
10 12 3 0
-
8/4/2019 C Language and DS Main
46/62
Insertion and deletion from linked list:
Item to be inserted
Insertion:
10 12 3 0
x
10 12 3 0
x
-
8/4/2019 C Language and DS Main
47/62
Deletion:
Note: similary insertion , deletion for double linked list.
Similary Stack , queue using linked list can be implemented.
Tress:
i) Its a non-linear data structure.
ii) Consists of finite set of elements, called nodes and finite set of directed
lines , called branches , which connect the nodes.
iii)The number of branches associated with the nodes is the degree of the
node.
10 12 3 0
-
8/4/2019 C Language and DS Main
48/62
iv) Incoming branch is known as indegree and out going branch or edge is
known as out degree.
Binary Trees:
i) A binary tree is a tree in which no node can have more than two
subtrees.
ii) Binary tree can be traversed in three different ways inorder, preorder,
post order traversal.
iii) In inorder traversal ,path is as leftnode, root, and right node. Whereas
in preorder , path is as root , leftnode, and right node.
Inorder traversal: CBDAEF
Preorder traversal : ABCDEF
Postorder traversal: CDBFEA
Binary Search Tree(BST):
i) Its a binary tree, if all left subtree are less than root, and right subtree
are greater or equal to root.
A
E
C
B
DF
-
8/4/2019 C Language and DS Main
49/62
ii) Each subtree is itself a binary tree.
Insertion: all insertion will be done at leaf nodes.
Inserting : 15
Graphs:
i) Its a collection of nodes called vertices , and collection of lines called
edges , connecting pair of vertices.
17
19
3
6
14 22
17
19
3
6
14 22
17
19
3
6
14 22
15
-
8/4/2019 C Language and DS Main
50/62
ii) Consists of Directed graph and Undirected graph.
a)
b)
Types of Graphs:
a) Weakly connected graph : directed graph is weakly connected if atleast
two vertices are not connected.
A
C
B E
F
D
A
C
B E
F
D
A
CB E
D
-
8/4/2019 C Language and DS Main
51/62
b) Strongly connected graph : directed graph is strongly connected if
there is path from each vertex to every other vertex in digraph.
F
A
C
B E
D
G
F
G
-
8/4/2019 C Language and DS Main
52/62
c) Disjoint graph : a graph is disjoint if it is not connected.
Graph storage techniques:
1) Adjacency matrix: we use vector to store the vertices and a matrix to
store the edges.
2) Adjacency List: we use a vector list to store the vertices and a linked list
to store the arcs or edges.
A
C
B E
D
F
G
-
8/4/2019 C Language and DS Main
53/62
Other traversal techniques:
1) Depth first traversal: in this , all nodes descendents are processed before
moving to an adjacent node.
DFT: ABEFCDGHI
Note: same as preorder for DFT
A
D
E
B
F
I
C
G H
A
G
x H
E
P
YJ
-
8/4/2019 C Language and DS Main
54/62
DFT: AXHPEYMJG
1:A 4: P 5: 6: Y 7: 8: 9:
2:x E E M M J
3: H G G G G G G
G
Breadth first traversal: in this, all adjacent vertices are processed beforeprocessing the descendants of a vertex.
BFT: ABCDEFGHI
M
A
D
E
B
I
C
G HF
A
G
x H
E
P
Y
M
J
-
8/4/2019 C Language and DS Main
55/62
BFT: AXGHPEMYJ
1:A 4: H 5: 6: 7: 8: 9:
2:x P P M Y
3: G E E Y J J
H
Searching and Sorting:
1) Selection sort: the selection sort divides the array into sorted and
unsorted sublists. In each pass, algorithm chooses the smallest
element from the unsorted sublist and swaps it with the element at
the beginning of the unsorted sublist.
Example:
Original list : 23, 78,45,8,32,56
Pass 1: 8,78,45,23,32,56
-
8/4/2019 C Language and DS Main
56/62
Pass 2: 8,23,45,78,32,56
Pass 3: 8,23,32,78,45,56
Pass 4: 8,23,32,45,78,56
Pass 5: 8,78,32,45,56,78
2) Bubble sort: the bubble sort divides the array into sorted and
unsorted sublists. In each pass, algorithm bubbles the smallest
element from the unsorted sublist into the sorted lists.
Example:
Original list : 23, 78,45,8,32,56
Pass 1: 8,23,78,45,32,56
Pass 2: 8,23,78,45,32,56
Pass 3: 8,23,32,78,45,56
Pass 4: 8,23,32,45,78,56
Pass 5: 8,78,32,45,56,78
-
8/4/2019 C Language and DS Main
57/62
3) Insertion sort: the insertion sort divides the array into sorted and
unsorted sublists. In each pass, algorithm inserts first element from
the unsorted sublist into appropriate position in the sorted lists.
Example:
Original list : 23, 78,45,8,32,56
Pass 1: 23,78,45,8,32,56
Pass 2: 23,45,78,8,32,56
Pass 3: 8,23,45,78,32,56
Pass 4: 8,23,32,45,78,56
Pass 4: 8,23,32,45,56,78
Divide and conquer sorting:
Quick sort:
i) quick sort is more efficient than bubble sort in that it requires
fewer exchanges to correctly position an element.
ii) Basic principle is to pick one element in the array and rearrange
the remaining elements around it. The selected element is called
pivot.
-
8/4/2019 C Language and DS Main
58/62
iii) All elements lesser than pivot are moved to the left and all
greater or equal to pivot are moved towards right of pivot.
Example:
a: 36,57,44,25,19,28,89
b: 25,19,28,36,57,44,89
c: 19,25,28, 36,57,44,89
d: 19,25,28, 36,44,57,89
2) Merge sort:
-
8/4/2019 C Language and DS Main
59/62
i) Its a divide and conquer algorithm.
ii) Main process will be to divide the list to be sorted into two smaller
sublists and repeat the process untill elements in the sublists get
sorted.
iii) To divide will use first + last element /2 , considering upper bound
value.
Example:
44,36,57,19,25,89,28
44,36,57,19 25,89,28
44,36 57,19 25,89 28
44 36 57 19 25 89 28
36,44 19,57 25,89 28
19,36,44,57 25,28,89
-
8/4/2019 C Language and DS Main
60/62
Note: Efficiency of bubble sort is O(n2)
Efficiency of selection sort is O(n2)
Efficiency of insertion sort is O(n2)
Efficiency of quick sort is O(nlogn)
Efficiency of merge sort is O(nlogn)
Searching :
1) Linear or Sequential search:
i) Its used when list is not in ordered.
ii) We start searching from the beginning of the list until we
get or until we sure that the element is not there in the list.
Consider list:
4,21,36,14,62,91,8,22,7,81,77,10
To search : 62
Index 0( 62!=4)
Index 1( 62!=21)
Index 2( 62!=36)
Index 3( 62!=14)
-
8/4/2019 C Language and DS Main
61/62
Index 4( 62==62) so element found
2) Binary Search:
i) Its used when the list is sorted.
ii) Its faster than sequential search.
iii) Sorted list will be divided into two halves , and element to
be searched will be compared will greater, than only right
subtree will be searched or else left. This process will be
followed until the element obtain or not found.
iv) Mid=(first+last)/2
Consider list:
4,7,8,10,14,21,22,36,62,77,81,91
To search : 22
i) Fir:0,mid:5,last:11
22>21
ii) 4,7,8,10,14,21,22,36,62,77,81,91
Fir:6,mid:8,last:7
22
-
8/4/2019 C Language and DS Main
62/62
Element found.
Note: Efficiency of sequential search is O(n)
Efficiency of binary search is O(logn)