data structures made simple

173

Upload: raghav-agrawal

Post on 20-Jan-2016

86 views

Category:

Documents


0 download

DESCRIPTION

covers data structures in concise,very good book for revising your concepts quickly

TRANSCRIPT

Page 1: Data Structures Made Simple
Page 2: Data Structures Made Simple

DATA STRUCTURES IN CMADE SIMPLE

( Second Edition)

KANNAN BALAKRISHNAN

SUMI HARIDAS

UMESH RAM

2011

Page 3: Data Structures Made Simple

Preface

For many years the authors have felt the need of a simple book in data structures. This book is writtenespecially for students in undergraduate classes.We have included basic concepts like stacks ,queues, linked lists, graphs, trees, searching and sortingalgorithms in this book.Even though we do not claim any in depth treatment of the subject in this book,we hope that it will be surely useful for students who are studying data structures in C for the firsttime.Many programs are included in the book. Also a companion blog i s available athttp://dssimple.wordpress.com .

We hope that this book will be of great use to students.

Cochin 24.11.11 Authors

Page 4: Data Structures Made Simple

TABLE OF CONTENTSChapter 1Pointers1.1 What Is A Pointer?1.2 Pointer Declaration1.3 Pointer Arithmetic1.4 Accessing Variables Using Pointer1.5 Address Operator (&)1.6 Dereferencing Operator (*)1.7 .One And Two Dimensional Arrays Using Pointers1.8 Void Pointers1.9 Pointers In Function Arguments1.10 Recursion1.11 Direct Recursion1.12 Indirect Recursion1.13 Array Of Pointers1.14 Pointer To Pointer1.15 Pointers To Strings1.16 Pointers to functionsExercisesChapter 2Structures and Unions2.1 Definition2.2 Accessing The Members Of A Structure2.3 Array Of Structures2.4 Structures Within Structure (Nested Structure)2.5 Pointers To Structures2.6 Structure In Functions2.7 Unions2.8 Difference and Similarity Between Structure And UnionExercisesChapter 3Strings and String Operations3.1 Strings3.2 Strlen()3.3 Strcmp()3.4 Strcat()3.5 Strcpy()3.6 Pattern Matching3.7 Dynamic Memory Allocation3.8 Malloc()3.9 Calloc()

Page 5: Data Structures Made Simple

3.10 Realloc3.11 Freeing MemoryExercisesChapter 4Sorting and Searching4.1 Sorting4.2 Different Sorting Techniques4.3 Bubble sort Implementation4.4 Selection sort4.5 Selection sort implementation4.6 Insertion sort4,7 Insertion sort Implementation4.8 Quick sort4.9 Quick sort implementation4.10 Merge Sort4.11 Merge Sort Example4.12 Bucket Sort4.13 Heap Sort4.14 Comparison Of Different Sorting Algorithms4.15 Searching4.16 Linear Search4.17 Binary Search4.18 Difference between Linear Search & Binary SearchExercises5Chapter 5 Stacks and Queues5.1 Stack5.2 Implementation of Stack using Arrays and pointers5.3 Applications of Stacks5.4 Queues5.5 Circular Queue5.6 Priority Queue5.7 Dequeue5.8 Input Restricted Dequeues5.9 Output Restricted Dequeues5.10 Applications of QueuesExercisesChapter 6 Linked lists6.1 Linked List6.2 Creation of Linked List6.3 Inserting Node6.4 Deletion of Nodes6.5 Doubly Linked List6.6 Operations on Doubly Linked List6.7 Circular Linked List

Page 6: Data Structures Made Simple

6.8 Circular Doubly Linked List6.9 Advantages/Disadvantages of Linked ListExercisesChapter 7 Trees7.1 Tree7.2 Root7.3 Degree7.4 Path length7.5 Level7.6 Forest7.7 Labeled Trees7.8 Binary Tree7.9 Application Of Trees7.10 Binary Tree Operations7.11 Tree Traversal Methods7.12 The Binary Search Tree7.13 Threaded Binary Tree7.14 Use Of Threaded Binary TreeExercisesChapter 8 Graphs8.1 Graphs8.2 Definition8.3 Adjacency List Representation8.4 DFS And BFS8.5 Depth First Search (DFS)8.6 Breadth First Search (BFS)8.7 Shortest Path8.8 Weighted Graph8.9 Dijkstra AlgorithmExercises

Page 7: Data Structures Made Simple

Chapter I Pointers in ‘C’

1.1. What is a pointer?

A pointer is a data type in C, which helps the programmer to access the memory locations ofvariables directly. A pointer contains a memory address which is the address of a variable. So, wedefine a pointer as follows Definition: A pointer is a variable that contains the address of another variable. We can have a pointer to any variable type. Using pointers complex data types can be declared andaccessed efficiently.

1.2 Pointer Declaration: The syntax of declaring a pointer is type *pointerName. The type in the above declaration is called the base type of the pointer. Example: char *x declares x as a pointer to a character variable and int *y says that y is a pointer to an integervariable. When p is a pointer to a variable of integer type, we say that the base type of p is integer. Similarlywhen q is a pointer to a float variable, we say that the base type of q is float and so on.

After declaring a pointer variable one must assign values to it. That is the pointer must be assigned tosome address. We can assign value to pointer in same way as any other variable data type.

int m, n;

Page 8: Data Structures Made Simple

int *p,*p1; P=&m;

Here the memory address of variable m is assigned to a pointer variable p. We are getting the addresslocation of the variable, not the content of the pointer variable. •

• Sum =*p1; • Here the content of the pointer variable p1 is assigned to the variable sum. That is, value of p1 is the address of the integer variable sum.

Figure 1.1 A pointer to p1 to an integer variable sum

Program to display the address and contents of a pointer is given next.

Program1.1#include<stdio.h> void main() { int x; int *p; // Here A pointer variable of base type integer is declared x=50; p=&x; //The pointer variable p is assigned the address of x printf(“Value of x is %d\n”,x); printf(“Value of the variable pointed by p is %d\n”,*p); printf(“Address of x is %d”,p); getch(); }

Page 9: Data Structures Made Simple

Output of the program Value of x is 50 Value of the variable pointed by p is 50 Address of x is 43522

1.2. Pointer Arithmetic

C language supports four arithmetic operations on pointers.

• Addition + • Subtraction - • Incrementation ++ • Decrementation - -

Here ++ increments the pointer to the address of the next memory location of the same type variable.The increment is done not by one but by the number of bytes required for the data type. That is if aninteger is 4 bytes, ++ will increment an integer pointer by 4 and not by 1. Similarly for otheroperators. Also subtraction of a pointer p2 from a pointer p1 is defined only if p1 and p2 are pointers of thesame base type.

Page 10: Data Structures Made Simple

Program illustrating pointer operations Program1.2

#include <stdio.h>void main(){int v,w ,*p,*q;v=80;w=90;p=&v;q=&w;printf("Value of p before increment operation=%u \n",p);p++;printf("Value of p after increment operation=%u\n",p);p--;printf("Value of p after decrement operation=%u\n",p);printf("Value of q=%u\n",q);printf("Value of p-q=%u\n",p-q);}

Output of the programValue of p before increment operation=4276350260Value of p after increment operation=4276350264Value of p after decrement operation=4276350260Value of q=4276350256Value of p-q=1

1.3. Accessing Variables Using Pointer

In C you can see two type of unary operators for declaring a pointer type variable. They are listedbelow, • Address operator & • Dereferencing operator *

1.4. Address Operator(&)

Address operator can be represented by the combination of &(ampersand) with a pointer variable.Ampersand is a unary operator that returns memory address to its operand. For example: p =&x;

Page 11: Data Structures Made Simple

The pointer operator & returns the address of the variable following it. So we can say that ‘p’ isassigned the address of x.

1.5. Dereferencing Operator(*)

This can be represented the combination of *(asterisk) along with the variable. Asterisk should bebefore the variable name. It is also a unary operator that returns the value of the variable located atthe address. For example: a=*p; Here a gets the value pointed by the pointer p.

1.5.1.1.1.1. One and Two Dimensional Arrays Using Pointers

Pointers and arrays are equivalent in the following sense. The name of the array acts as a pointer to the first element of the array. Let us explain this with two examples: int a [50]; The above statement declares an array of integers of size 50, having elements a[0], a[1] ,.., a[49].This is a one dimensional array. The variable a can be used as a pointer to the array. Variable a will point to the starting address ofthe array, that is a [0]. The elements of this array are a [0], a[1], …, a[49]. They are integer variables. Logically, these elements are stored in 50consecutive memory locations. Therefore a pointer variable of base type integer can point to theseelements. We know that int *ip declares ip as an integer type pointer. Now the two statements below, takentogether are equivalent to the statement a[3] = 7 ip = &a[3]; *ip = 7; taken together are equivalent to the statement a[3] = 7

Also the statement ip = a is equivalent to saying that ip = &a[0]. Similarly, ip = a+5 is equivalent tosaying that ip = &a[5].Generalizing ,We can say that the following is true.

If a is an array of size n, having elements a[0], …… a[n-1], of a particular data type, then a is a

Page 12: Data Structures Made Simple

pointer of that base type whose value is the address of a[0] and a+k points to a[k] for any k between1 and n-1. A two dimensional array can be represented by a matrix.The next figure shows a two-dimensionalarray

Figure 1.2 A two dimensional array b[3][4] with three rows and four columns. The following statement declares a two-dimensional array. float b[3] [4].

C treats a two dimensional array as a one dimensional array of rows. Each row itself is again a onedimensional array.

Now b will point to b[0],which is the first row of the array. Also b+1, b+2, ….. Will be used toaccess to successive rows of the array b[ ][ ].Now b[0], is the first row .Since the first row is a onedimensional array,b[0] is a pointer to the first element b[0][0] of that array . Similarly b[1] is apointer to the first element b[1][0] in the second row and so on. Also b[0]+j is a pointer to b[0][j].Again *(b+i) is actually same as b[ i ] and *(*(b+i)+j) is the pointer representation of b[i][j].

Program to display the content of a one dimensional array using pointers: Program1.3

Page 13: Data Structures Made Simple

#include<stdio.h> main() { int a[4]={1,2,3,4}; int *p1; int i,s,t1; s=4; printf("Display the contents of array\n"); for(i=0;i<=s-1;i++) { t1= *(a+i) ; printf("value is =%d\n",t1); } }

Output of the program Display the contents of array

value is =1value is =2value is =3value is =4

Program to show contents of two dimensional array using pointers

Program1.4 #define maxsize 50

#include<stdio.h> void main() { int b[maxsize][maxsize],n_of_rows, n_of_cols, i,*p, j, tvalue; printf("Enter The number of rows: "); scanf("%d",&n_of_rows); printf("Enter the number of columns: "); scanf("%d",&n_of_cols); for(i=0;i<=n_of_rows-1;i++) { for(j=0;j<=n_of_cols-1;j++) { printf("Enter the (%d,%d) element ", i,j); scanf("%d",&b[i][j]);

Page 14: Data Structures Made Simple

} } printf("Contents of array\n"); for(i=0;i<=n_of_rows-1;i++) { for(j=0;j<=n_of_cols-1;j++) { tvalue=*(*(b+i)+j); printf("%d\t",tvalue); } printf("\n"); }}Output of the programEnter The number of rows: 3Enter the number of columns: 4Enter the (0,0) element 1Enter the (0,1) element 2Enter the (0,2) element 3Enter the (0,3) element 4Enter the (1,0) element 5Enter the (1,1) element 6Enter the (1,2) element 7Enter the (1,3) element 8Enter the (2,0) element 9Enter the (2,1) element 10Enter the (2,2) element 11Enter the (2,3) element 12Contents of array1 2 3 45 6 7 8 9 10 11 12

1.7 Void Pointers

Pointers to different data types are considered different. There is no implicit conversion from onetype of pointer to the other. In order to overcome this inconvenience, we use a pointer to point to multiple data types. If we don’tknow what kind of value a pointer will point to then we can declare a “void pointer”. Void pointers are commonly used in the parameter list of built–in function, such as memcpy andmemset. Void pointer can point to any data type and any other pointer can be assigned to it. But it is notconsidered good practice to use a void pointer unless it is required in very special cases.

1.9 Pointers in Function arguments

Page 15: Data Structures Made Simple

In function declaration you can use pointers frequently. Using pointers as arguments, we can easilyrewrite a complex function. Pointer arguments enable a function to access and change variables thatare passed to it.

Program illustrating the use of pointers in functions.Program1.5

#include<stdio.h>

void main()

{ int value1,value2; value1=100; value2=200; clrscr(); printf(“values before swap()operation is %d%d\n\n”, value1, value2); swap(&value1,& value2); //Calls function printf(“values after swap()operation is %d %d\t\n\n”, value1, value2); getch(); return(0); } void swap(int *value1,int *value2) { int tempvalue; tempvalue=* value1; *value1=*value2; *value2=tempvalue; } Output of the program values before swap() operation is100 200 values after swap() operation is 200 100

Page 16: Data Structures Made Simple

1.10 Recursion

Page 17: Data Structures Made Simple

Definition:

Recursion is a technique widely used to make write complex functions in a simple way. A functionwhich invokes itself directly or indirectly is called as recursive function.

Page 18: Data Structures Made Simple

Example: The Factorial of an integer n>=1 is defined as follows

Page 19: Data Structures Made Simple

n! = 1 * 2 * , . .*n We can use this definition to write int factorial1 (int n){ int i; int s; s = 1; for (i = 1; i <= n; i++) { s = s * i; } return s; } Using recursion we can rewrite the above function. We know that n!=(n-1)!*n for n >0 . So we canrewrite the above function using follows:

int factorial2 (int n) { If (n<=1) return 1; return n * factorial2 (n - 1)); } This function is an example of implementing recursion in C. Comparing the two problems, the second version is much simpler than first.

There are two types of recursion: 1. Direct Recursion 2. Indirect Recursion

1.11 Direct Recursion

A directly recursive function is a function which contains a direct call to itself. For example, considerthe function:

Page 20: Data Structures Made Simple

int f1 (int n) { if (n <= 0) return n; return (n+ f1(n- 1)); } The above function contains a call to itself, and so it’s directly recursive. 1.12 Indirect Recursion

A function f1 is indirectly recursive if it contains a call to another function which in turn calls f1 . The following functions are indirectly recursive. int f1(int n) { if (n<= 0) return n; return (n+ f2(n)); } int f2(int m) { return f1(m - 1); } Here function f1 calls another function f2, which in turn calls the first function f1. So we say that thisfunction is indirectly recursive.

1.13 Array of Pointers

When you have a large array of data items, names for example, and you want to access them in sortedorder one method is to use an array of pointers. We can use array of pointers like any other array. Thedeclaration for an integer pointer array p1 of size 15 is

int *p1 [15]; The elements of above array are p1 [0], p1 [1],...,p1 [14], all of them pointers of base type integer.

Page 21: Data Structures Made Simple

An array of pointers can be defined in such a manner that each item of the array point to an item in thedata array. We will illustrate this with a figure.

A

B

0

Rajesh

1

Suresh

2

Aneesh

3

Hridaya

4

Joseph

5

Fransis

6

Kannan

Now A is the array of pointers, pointing to the data array B. Instead of sorting B in alphabetical order,we just sort A in the alphabetical order of elements of B and access elements of B from elements ofA. This type of sorting has the following advantages. 1. The original data is not changed 2. We save time, because sorting of pointers is simple, compared to sorting of strings. 3. No additional space required.

Program illustrates the use of array of pointers. Program1.6

Page 22: Data Structures Made Simple

# include<stdio.h> main() { Char *p [4]; p[0]=”Sunil”; p[1]=”Raj”; p[2]=”Alok”; p[3]=”Syam”;

Printf (“content of pointer 1 is=%s\n”, p [0]); Printf (“content of pointer 2 is=%s\n”,p[1]); Printf (“content of pointer 3 is=%s\n”,p[2]); Printf (“content of pointer 4 is=%s\n”,p[3]); getch(); }

Output of the program content of pointer is 1=Sunil content of pointer is 2=Raj content of pointer is 3=Alok.

1.14 Pointer to Pointer

A pointer to pointer is a form of multiple indirections. The first pointer holds the address of the second pointer and the second pointer points to a variable.

Pointer�pointer�Variable. The general Syntax for the declaration: <Data type> **<pointer name> Eg: int **p1; Program illustrates the use of Pointer to Pointer

Page 23: Data Structures Made Simple

Program1.7

#include <stdio.h> main() { int v; int *p1,**p2; v=50; printf("number is =%d\n",v); p1=&v; p2=&p1; printf("address of the number is = %u\n",&v); printf("value pointed by pointer2 =%u\n",*p2); printf("value of pointer1 =%u\n",p1); printf("Value pointed by pointer1=%d\n",*p1); printf("Value pointed by the pointer pointed by pointer2=%d\n",**p2); }

Output of the program number is =50 address of the number is = 4277627172 value pointed by pointer2 =4277627172 value of pointer1 =4277627172 Value pointed by pointer1=50 Value pointed by the pointer pointed by pointer2=50

1.15 Pointers to strings

String operations in c are mainly performed with the help of pointers. String is a sequence ofcharacters; string is accessed in a strictly sequential manner. That is why we use pointers in stringoperation. String always terminated by a Null character or ‘\0’. The following program is an example Program for pointers to strings

Page 24: Data Structures Made Simple

Program1.8 #include<stdio.h> #define maxsize 60 void main() { char s[maxsize]; printf(“enter the string:”); gets(s); display(&s);// calls the function printf(“\n”); getch(); } void display(char *s) { while(*s!=’\0’) { printf(“%c”,*s); s++; } }

Output of the program

enter the string: pointers to string pointers to string

Pointer to Functions Just like any other variable,a function is also stored at a memory location and has an address. Thename of the function is a pointer to it. We can also declare pointer to a function.

The following program illustrates an example for function pointer.

Page 25: Data Structures Made Simple

Program1.9

#include <stdio.h> void sampleFunction(int n) { printf( "%d\n", n ); } int main() { void (*pointer_to_function)(int);//Declaring a function pointer pointer_to_function = &sampleFunction;//Intitialising the function pointer pointer_to_function(

10 );// calling the function using the function pointer getch(); return 0; } Output of the program 10

Page 26: Data Structures Made Simple

Exercises

1. Explain the pointer declaration in C language. 2. How do you declare a pointer to a function? 3. Explain dereferencing operator. 4. What is a void pointer? 5. How can we access a one dimensional array using pointer? 6. Explain pointers to strings. 7. Explain the different types of recursion. 8. Explain pointer arithmetic with example. 9. How can you create array of pointers? 10. Explain about addressing and dereferencing operators.

Page 27: Data Structures Made Simple

Chapter II Structures And Unions 2.1 Definition A structure is used to represent a related group of items. Each individual item in the structure iscalled as a member. Example: struct employee { char empName[10]; char address[20] ; char place[10]; int pinCode; } emp1;

Declares a structure variable emp1 of the type employee. Also the same declaration can be written as struct employee { char empname[10]; char address[20] ; char place[10]; int pincode; }; struct employee emp1;

Also the type definition can be used to define a structure.

2.2Accessing the members of a structure

To access the members of a structure the ‘.’ operator is used. Example: emp1.empname will refer to the empname field in the structure variable

Page 28: Data Structures Made Simple

emp1.

2.3 Array of structures

Suppose you want to store the details of 100 students in an array. Each student has a roll no. and nameand the structure student is defined as, struct student { int Roll no; Char Name[20]; }; Now you can declare an array of size 100 as shown below: Student NRoll [100]; Each element of the array can be the details of the student. That is an array of structures can be usedjust like an ordinary array, to store data having structure.

Program illustrates the use of array of structures.Program2.1

#define max 3 #include<stdio.h> void main () { structure student { char name[20]; int Rollno; }; struct student class[max]={{“Ramya”,23},{“Sita”,45},{“Geeta”,47}}; int i; printf(“List out the contents of Structure\n”); for(i=0;i<=max-1;i++) { printf(“name:%s\n”,class[i].name);

Page 29: Data Structures Made Simple

printf(“Roll no:%d\n”,class[i].Roll no); } } Output of the program List out the contents of Structure Ramya 23 Sita 45 Geeta 47 2.4 Structures Within Structure (Nested Structure)

Definition: A structure having another structure as a member is called a nested structure. A member of structure may be another structure. When a structure is declared as the member ofanother structure we call it as nested Structure. Using this feature we can build complex structures.

Example: struct date { int day; int month; int year }; struct student { char name[20]; int roll no; struct date dob; };

2.5 Pointer to Structures

Page 30: Data Structures Made Simple

We can declare pointers to structures the same way we declare any other pointers: by precedingthe variable name with an asterisk in the declaration. struct Complex { int x; float y }; struct complex *p1,*p2; In the above declaration p1, p2 are pointer variables holding the address of a variable of typestructure complex.

2.6 Structure in Functions

We can pass a structure variable as a parameter to a function just as we pass any other variable.The following program is an example for passing a structure as a parameter to a function. Program2.2

#include<stdio.h> struct dob //Declaring a structure { int day;

int month;int year;

};void main() { struct dob d1; //Declaring a structure variable d1.day=26; d1.month=8; d1.year=2007; display(d1); getch(); }

Page 31: Data Structures Made Simple

void display (struct dob n); { printf(“date is%d/%/d/%d\n”,n.day,n.month,n.year); } Output of the program date is 26 /8/ 2007

2.7 Unions

We have a situation where we want to interpret the value of a variable depending upon the contextof the variable. Union stores values of different data types in a single location. This saves memory.Declaration and usage of union is same as that of structure with the keyword struct replaced by thekeyword union.

For example a merchant may sell items by number or by weight (example: two bottles of squash and3.5 k.g sugar).In this case the field quantity sold can be taken as a union of an integer and a float. . Declaration union quantity { int no_of_items; float weight; } ;

struct saledetails { int type; union quantity quantity_sold; };

Program to illustrate union

Page 32: Data Structures Made Simple

Program 2.3

#include<stdio.h> typedef union { int trucknumber; char truckname[8]; }load;

typedef struct { char itemname[10]; load item; }goods;

int main() { goods gd[10]; int i,n; printf ("Enter no of shipping items\t"); scanf("%d",&n); for (i=0; i<n; i++) { printf("Enter the itemname ,trucknumber\t"); scanf("%s",gd[i].itemname); scanf("%d",&gd[i].item.trucknumber); } for (i=0;i<n;i++) { printf("\nItemname=%s",gd[i].itemname); printf("\nTruckNumber=%d",gd[i].item.trucknumber); } printf("\n");

Page 33: Data Structures Made Simple

for (i=0; i<n; i++) { printf("Enter the truckname\t"); scanf("%s",gd[i].item.truckname); } for (i=0;i<n;i++) { printf("\nTruckname=%s",gd[i].item.truckname); printf("\nTruckNumber=%d",gd[i].item.trucknumber); } getch(); return 0;

} Output of the Program Enter no of shipping items 2 Enter the itemname ,trucknumber Steel 5678 Enter the itemname ,trucknumber Nickel 6665

Itemname=Steel TruckNumber=5678 Itemname=Nickel TruckNumber=6665 Enter the truckname Bangar Enter the truckname Star7

Truckname=Bangar TruckNumber=1735287106 Truckname=Star7 TruckNumber=1918989395

In the above program you can see that when we try to print the truck number after reading truck nameit is showing some unknown value. This is because the same space is used for storing truck numberand truck name. So truck name overwrites the truck number.

Page 34: Data Structures Made Simple

2.8 Difference and similarity between structure and union

The differences between structure and union in c are:

3. Union allocates the memory equal to the maximum memory required by any member of theunion, but structure allocates the memory equal to the total memory required by all the members.

2. In union, one block is used to store all the members of the union. That is, all the membersshare same memory. In the case of a structure, each member has their own memory space.

The similarities between structure and union are

2. Their declarations have similar syntax. 2. Accessing members also have the same syntax (using the . Operator) 3. Structures as well as unions can be nested inside other structures or unions.

Page 35: Data Structures Made Simple

Exercises

1. Explain the declaration and initialization of structures. 2. Explain structure within structure. 3. Explain the use of pointers in structure. 4. Explain union. 5. What is the difference between structure and union? 6. What you mean by array of structure? 7. Develop a c program to read the following information from the key board • Employees name • Employees code • Age • designation and represent it as a structure.

Page 36: Data Structures Made Simple

Chapter III Strings and String Operations

3.1 Strings In C, a string is viewed as an array of characters. A special character called null denoted by “\0”ends the string. The following is an example of a string stored as an array of characters.

I

L

O

V

E

I

N

D

I

A

\0

C provides for many strings operators. Let us discuss the following in detail.

Function

Parameters

Use

strlen

String

Length of string

strcat

String1, string 2

Concatenate of string 2 to 1

strcmp

String 1, string2

Compare two strings

strcpy

String 1, string2

Copy string 2 to string 1

3.2 strlen ( )

We are using strlen() for knowing the length of the string. The strlen ()checks each array position tosee whether it is null or not. N=strlen (string); Sample program to check the length of the string is given below Program 3.1

Page 37: Data Structures Made Simple

#include < stdio.h > #include < string.h> void main() { char name[100]; int length; printf(“Enter the string=”);

gets(name); length=strlen(name); printf(“\nNumber of characters in the string is=%d”,length); }

Output of the programEnter the string= GeethaNumber of characters in the string is=6.

Implementation of string length operations using user-defined functions is as follows. int strlen(char s1[ ]){int k;

for(k=0;s1[k]!=’\0’;k++){

continue;}

return(k);}

3.3 strcmp()

Page 38: Data Structures Made Simple

This function is used to compares two strings. This function returns value 1 if the two strings aresame and it will returns 0 otherwise. This is one of the most commonly used of the string handlingfunctions. Example: strcmp(char *a1, char *a2);

Implementation of string comparison operations using user-defined functions is as follows.

int strcmp(char a1[ ], char a2[ ]){int j,j1,j2;j1=strlen(a1);j2=strlen(a2);if (j1!=j2)return(0);for(j=1;j<j1,j++){if(a1[j]!=a2[j])return(0);}return(1);}

3.4 strcat() strcat (string1,string2) string1 and string2 are strings. When the function strcat is executed string2 is appended to string1.The string at string2 remains unchanged.

strcpy (string1,”sri”); strcat (string2,”devi”); printf (“%s”,strcat(string1,string2); From the above program segment the value of string1 becomes sridevi string at str2 remainsunchanged as devi.

Page 39: Data Structures Made Simple

The following shows the implementation of strcat as a program

Program3.2

#include<stdio.h> void main() { char s1[10 ],s2[10 ],s3[30]; int k=0,k1; printf("Enter the first string\n"); gets(s1); printf("Enter the second string\n"); gets(s2); for(k=0;s1[k]!='\0';k++) s3[k]=s1[k]; k1=k; k=0;

for(k=0;s2[k]!='\0';k++) s3[k1+k]=s2[k]; k1=k1+k; printf("The concatenated string is given below\n"); for (k=0;k<k1;k++) printf ("%c",s3[k]); getch(); }

Output of the program

Page 40: Data Structures Made Simple

Enter the first stringGood morningEnter the second stringIndiaThe concatenated string is given belowGood morning India

3.5.strcpy()

This is used to copy one string to another char *strcpy(char *s4, char *s5); Copy the string pointed to by s5 into the string pointed to by s4,

C does not allow you to assign the characters to a string directly as in the statement Name=”sandya”; instead use strcpy like this strcpy (Name,”sandya”); In the above example sandya is assigned to the string called Name.

Implementation of string comparison operations using user-defined functions is as follows.

void strcpy(s,s1){

int k;char s[],s1[];for(k=0;s1[k]!=”\0”;k++){s1[k]=s[k];}

Page 41: Data Structures Made Simple

s1[k]=”\0”;}

3.6 Pattern Matching Pattern matching in strings is the process of checking whether a given pattern of letters (string) occuras a substring in a given string. Here we have two inputs the given string, and the pattern string.Clearly the length of the pattern should not exceed the length of the given string.

3.7 Dynamic Memory Allocation

The C compiler needs to allocate memory to variables. This Memory allocation can be classified intotwo types.

1. Static or compile time and 2. Dynamic or run time.

In static memory allocation memory required for a variable is allocated at the time forcompilation. For example, if you declare x as a float variable by float x; Then the memory required for x is the size of a float and allocated at the time of compilation. Similarly if you want to declare an array of 10 integers by int a [10]; Then 10 times size of an integer is reserved at the compile time. This has the followingdisadvantages. 1. You cannot use more memory than what you have already allocated. 2. If you use less memory than allocated, the remaining memory is wasted. This causes inefficient useof memory. Dynamic memory Allocation allocates memory at run time. The following functions are used in C to do the dynamic memory allocation. malloc, calloc, realloc, free.

Page 42: Data Structures Made Simple

3.8 Malloc

This function is used to allocate a heap of storage. The name stands for memory allocation. The general declaration of malloc function, char *malloc (size) int size; The following program segment illustrate the use of malloc function struct linkedlist { int value struct linkedlist *value; }; struct linkedlist *pnode; pnode=(struct linkedlist*)malloc (sizeof(struct linkedlist)); 3.9 Calloc Calloc is used to allocate contiguous memory on an element-by-element basis. The name stands forcalculated allocation. This is useful in the case of array like structure where continuity of memoryrequired. void calloc(elements, element_size); Thus to assign 500 integer elements that are all initially zero you would do: int *pnode; pnode = (int *) calloc(500, sizeof(int));

The following program illustrates the dynamic allocation of arrays using calloc Program 3.3 #include<stdio.h>

int main(){

int *array,n,i;printf("Enter the size of array\t");scanf("%d",&n);array=(int*)calloc(n,sizeof(int));printf("Enter %d numbers\n",n);for(i=0;i<n;i++)scanf("%d",&array[i]);printf("Numbers Entered \n");for(i=0;i<n;i++)

Page 43: Data Structures Made Simple

printf("%d\t",array[i]);getch();return 0;

}

Ouput of the Program

Enter the size of array 10Enter 10 numbers19 29 39 495 96 97 98 90 80 79Numbers Entered19 29 39 495 96 97 98 90 80 79

3.10 Realloc Realloc is a function which attempts to change the size of a previously allocated block of memory.(Realloc stands for reallocate) The new size can be larger or smaller. If the block is made larger thenthe old contents remain unchanged and memory is added to the end of the block. If the size is madesmaller then the remaining contents are unchanged The general declaration for the realloc function is given below char *realloc (oldblocksize,newblocksize) int oldblocksize; int newblocksize;

Page 44: Data Structures Made Simple

3.11 Freeing Memory

Memory allocated with malloc lasts as long as you want it. When you have finished using a portion ofmemory you should always free(deallocate) it. If you want to deallocate the memory that allocate bymalloc function call, we can use function free (). The general declaration for free () function is given below int free (pnode) char *pnode; The following program illustrates the use of malloc( ) to allocate some bytes then use realloc( )to allocate more bytes and finally use free( ) to deallocate the allocated bytes.

Page 45: Data Structures Made Simple

Program 3.4

#include<stdio.h>int main(){char *p,size,newsize;printf("Enter the size\t");scanf("%d",&size);

p=(char *)malloc(size); //allocating size bytes to character pointer p.printf("Enter a string of length %d\t",size);getchar();gets(p);puts(p);printf("Enter the new size\t");scanf("%d",&newsize);

p=realloc(size,newsize); //reallocating newsize bytes to character pointer p.printf("Enter a string of length %d\t",newsize);getchar();gets(p);puts(p);free(p); //deallocating memory.printf("Memory is deallocated\n");getch();}

Output of the program

Enter the size 5Enter a string of length 5 abcdeabcdeEnter the new size 7Enter a string of length 7 abcdefgabcdefgMemory is deallocated

Page 46: Data Structures Made Simple

Exercises

1. How we are using pointers to handle strings? 2. What are the different string handlings functions? 3. Write a c program to find out the length of a string. 4. Write a C program to print the string abbreviation of an inputted string. 5. Explain the different types of memory allocation. 6. What is the disadvantage of static memory allocation ? 7. Explain Dynamic memory allocation. 8. What are the advantages of dynamic memory allocation? 9. How can you change the size of previously allocated memory? 10.How can you deallocate a memory?

Page 47: Data Structures Made Simple

Chapter IV Sorting and Searching

4.1 Sorting

Sorting is arranging data items in some order. For example, we may want to arrange 10 numbers in ascending (increasing) order, or a teacher mayneed to arrange a list of students in alphabetical order, or he may want to arrange the marks ofstudents in descending (decreasing)order. For all such purposes we use sorting. Example: The numbers 9,10,5,6,3,8 when sorted in ascending order becomes 3,5,6,8,9,10, and when sorted indescending order, they are arranged as 10,9,8,6,5,3. There are two types of sorting 1. Internal sorting. 2. External sorting. 1. Internal sorting: This means data for sorting is available in memory. 2. External sorting: Some times it happens that data item for sorting is too large to occupy in memory. So we need to storesuch items in secondary storage devices then we have to apply external sorting.

4.2 Different Sorting Techniques

1. Bubble sort It is the oldest and simplest sorting technique. In bubble sort pairs of adjacent values are sorted bycomparing the values with each other. Therefore an item bubbles the entire list, until it reaches onevalue that compare to be smaller than the first value. Suppose we have an n number of elements in ourlist to sort, then we have to do (n-1) passes (iterations).Advantages: Bubble sort is simple and easy to implement.

Page 48: Data Structures Made Simple

Disadvantages: For n no of elements there will be n-1 iterations. So Bubble sort is considered as the most inefficientsorting algorithm.

Best case: Under best case if array is already sorted then also the outer loop to execute n-1 times. Timecomplexity for best case is O (n2).

4.3 Bubble sort implementation

In order to explain bubble sort we are taking an array of three items. This is shown below.

a[0]

160

a[1]

155

a[2]

120

3. In first iteration i=0, 0th element 160 is compared with 155. Since 160 is greater than 155, weinterchange them. Resulting array is 155,160,120.Now 160 is in a[1]th position. It is compared with the a[2].120 is less than 160, so weinterchange them. Array is now 155,120,1602. For the second iteration 0th element 155 is compared with first element. Here 120 is less than155, so we interchange them. Resulting array is 120,155,160.Now 155 is in a [1], it is comparedwith a[2].155 is less than 160,we cannot interchange them. Now the array is in its sorted order.Resulting array is 120,155, 160.

a[0]

120

a[1]

155

Page 49: Data Structures Made Simple

a[2]

160

Program for bubble sort: Program 4.1

#include<stdio.h>#include<conio.h>void main(){int i,j,n,array[5],tempvalue=0;printf("Enter the size\n");scanf("%d",&n);printf("Enter %d numbers\n",n);for(i=0;i<n;i++){scanf("%d",&array[i]); }for(i=0;i<n;i++){for(j=0;j<n-1;j++){if(array[j]>array[j+1]){tempvalue=array[j];array[j]=array[j+1];array[j+1]=tempvalue;}}}printf("The list sorted in ascending order is\n");for(i=0;i<n;i++){printf("%d\n",array[i]);}getch();}

Page 50: Data Structures Made Simple

Ouput of the ProgramEnter the size5Enter 5 numbers9977886655The list sorted in ascending order is5566778899

4.4. Selection sort In selection sort we are taking the smallest item (unsorted) in the list, and swapping it with the item inthe very next position. Suppose we want to sort the given numbers in ascending order, 0th element iscompared with other elements present in the list, .If the 0th element is greater than the comparedelement then they are interchanged. After the first iteration the smallest element is placed in 0thposition. Similar procedure is repeated for the entire list of elements. Advantages: Simple technique and easy to implement. Disadvantages: Inefficient for large list of elements. Program for selection sort

4.5 selection sort implementation

We can explain the selection sort by taking an array of 4 items.

a[0]

250

a[1]

150

Page 51: Data Structures Made Simple

a[2]

200

a[3]

100

2. For the first iteration i=0, 0t h element is compared with a[1]. 150 is less than 250, weinterchange them. Resulting array is 150 250 200,100.a[0]t h element is again compared witha[2]th element, which is greater than a[0]th element so we can’t interchange them. Again 150compared with a[3].100 is less than 150, we interchange them. The resulting array is100,250,200,150.3. For the second iteration i=1, a [1] th element compared with a [2]. 200 is less than 250, weinterchange them. Resulting array is 100,200,250,150.

a [3]th element compared with a[1]. 150 is less than 200, we interchangethem. Resulting array is 100,150,250,200.3. For the third iteration i=2,250 is compared with a [3]. 200 is less than

250 we interchange them. Resulting array is

a[0]

100

a[1]

150

a[2]

200

a[3]

250

Program for selection sort Program 4.2

#include<stdio.h>

Page 52: Data Structures Made Simple

void main(){

int array[12],i,n,smallvalue,j,position,tempvalue;printf("Enter the size\n");scanf("%d",&n);printf("enter %d elements\n",n);for(i=0;i<n;i++)scanf("%d",&array[i]);for(i=0;i<n-1;i++){

smallvalue=array[i];position=i;for(j=i+1;j<n;j++){

if(array[j]<smallvalue){smallvalue=array[j];position=j;}

}tempvalue=array[i];array[i]=smallvalue;array[position]=tempvalue;

}printf("\n Sorted array is\n");for(i=0;i<n;i++){printf("%d\n", array[i]);}getch();

}

Output of the Program

Enter the size5enter 5 elements99663388

Page 53: Data Structures Made Simple

77

Sorted array is3366778899

4.6. Insertion sort Insertion sort is a simple sorting algorithm, in which the sorted array (or list) is built one entry at atime. The insertion sort works just like its name; it inserts each item into its proper place in the list.We use two lists to implement insertion sort. The insertion sort has a time complexity of O (n2).

Advantage: Comparatively simple and it is easy to implement. Disadvantage: Inefficient for large lists.

4.7. Insertion sort implementation Here we have an array a[3], consists of 3 elements. We can see how insertion sort is going toimplement for sorting numbers in ascending order.

a[0]

160

a[1]

152

a[2]

100

1. For the first iteration i=1, a[1] is compared with a[0].we have found that 152 is less than 160, we

Page 54: Data Structures Made Simple

interchange them. 2. For the second iteration i=2, the second element 100 is compared with 160.Then we interchange them.100 is again compared with 152. The resultingArray is shown below. a[0]

100

a[1]

152

a[2]

160

Program for Insertion sort: Program 4.3

#include<stdio.h>void main(){int array[12],i,j,n,tempvalue;printf("Enter the size of numbers to sort\n");scanf("%d",&n);printf("enter %d numbers\n",n);for(i=0;i<n;i++)scanf("%d",&array[i]);for(i=1;i<n;i++){tempvalue=array[i];j=i-1;while((tempvalue<array[j]&&(j>=0))){array[j+1]=array[j];j=j-1;}array[j+1]=tempvalue;}printf("Sorted array is \n");for(i=0;i<n;i++)printf("%d\n",array[i]);

Page 55: Data Structures Made Simple

getch();}

Output of the Program Enter the size of numbers to sort5enter 5 numbers9922557744Sorted array is2244557799

4.8Quick sort

The quick sort is one of the fastest sorting techniques. Quick sort is an algorithm using recursion.There are four steps in the algorithm. If there are no elements or just one element in the array to be sorted, return immediately. 1. Select an element in the array as a “pivot” point. Mainly we are taking the leftmost element in

the array 2. Split the array into two parts - one with elements larger than the pivot and the other with

elements smaller than the pivot. 3. Repeat the algorithm for both halves of the original array. The efficiency of the algorithm mainly depends upon which element is chosen as the pivot

element. The worst-case efficiency of the quick sort, O (n2), occurs when we have taken theleft-most element. As long as the pivot point is chosen randomly, the quick sort has itsalgorithmic complexity of O (n log n).

Advantage: Extremely fast one. Disadvantage: Very complex algorithm and highly recursive one.

Page 56: Data Structures Made Simple

4.9 Quick sort implementation We can explain the Quick sort by the following example. We have an array of 7Elements.

a[0]

56

a[1]

12

a[2]

25

a[3]

33

a[5]

100

a[6]

70

a[7]

80

There are a number of ways to pick the pivot element. In this example, we will use the first element inthe array as pivot element.Given a pivot, partition the elements of the array such that the resulting array consists of:

3.1. One sub-array that contains elements >= pivot3.2. Another sub-array that contains elements < pivot

56

12

25

33

100

70

80

Page 57: Data Structures Made Simple

Quick sort starts with 0th element 56. Read the elements from right to left. Compare element with 56on starting from right to left. Stop at the element which hasless value of that 56. The number is 33, we interchange them. Resulting array look like this

33

12

25

56

100

70

80.

We take 56 as the Pivot element. Because the elements of the array to left are smaller than 56;elements of the array to right are greater than 56. Here we are dividing the array into two parts, one isright side of 56, other one is left side of 56.The above procedure is repeated for the two sub arrays,until we get the sorted array. Program for Quick sort Program 4.4 #include<stdio.h> int main() { int array[30],n,i; printf("\nEnter size of the array :"); scanf("%d",&n); printf("Enter %d elements : ",n); for(i=0;i<n;i++) // reading elements scanf("%d",&array[i]); quickSort(array,0,n-1);// function to sort printf("\nSorted elements :"); for(i=0;i<n;i++) printf(" %d",array[i]); getch(); return 0; }

quickSort(int array[10],int left,int right) { int pivot,j,temp,i; if(left<right)

Page 58: Data Structures Made Simple

{ pivot=left; //choosing first element as pivot i=left; j=right;

/*Considering the pivot element array is subdivided into two arrays*/ while(i<j) { while(array[i]<=array[pivot]&&i<right) i++; while(array[j]>array[pivot]) j--; if(i<j) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } temp=array[pivot]; array[pivot]=array[j]; array[j]=temp; quickSort(array,left,j-1); //applying quick sort to left sub array quickSort(array,j+1,right); //applying quick sort to second sub array } }

Output of the program

Enter size of the array :10 Enter 10 elements : 88 55 99 22 44 66 11 43 57 21 Sorted elements : 11 21 22 43 44 55 57 66 88 99

Page 59: Data Structures Made Simple

4.10. Merge Sort Merge sort is another sorting algorithm which works in the following way. 3. Divide the element in to two parts. 4. Sort the two parts using merge sort algorithm 5. Merge the two sorted list in to a single sorted list. The heart of a merge sort algorithm is a procedure to merge two sorted list in to a single sorted

list. The time complexity of the algorithm is O(nlogn). Advantage: Marginally faster for larger sets. Disadvantage: At least twice the memory requirement of the other sorts:

4.11 Merge Sort Example Consider an array of 4 integers 7,3,5,4. Now merge sort first divides the array in to two sub array [7,3], and [5,4].In the next step[ 7,3] and [5,4 ] are divided in to [7]&[3] and [5]&[4].Now these two are merged back to form[3,7] and[4,5], which is again merged to form 3,4,5,7. The below figure explains the idea.

Page 60: Data Structures Made Simple

Program for Merge sortProgram 4.5 #include<stdio.h>#define maxsize 50void merge( int array1[maxsize],int start1,int end1, int end2){//merges two sorted sub arrays array1[start1],..., array1[end1] and//array1[end1+1]...// array1[end2] into a single sorted array.

int size1,size2,size3, index1,index2,index3, index4,i,j;int result[maxsize]; //A temporary array to store the resultindex1=start1;index2=end1+1;index3=start1;index4=start1; while((index1<=end1)&&(index2<=end2))if(array1[index1]<array1[index2]) //If an element in the first subarray// is lesser,move it to the result array{result[index3]=array1[index1];index1++;index3++;

}else{result[index3]=array1[index2]; //otherwise move the element of//the second part to the result arrayindex2++;index3++;}if(index1>end1) //first part is over.// So copy the second part to the result arraywhile(index2<=end2){result[index3]=array1[index2];index2++;index3++;

Page 61: Data Structures Made Simple

}else //second part is overwhile(index1<=end1){result[index3]=array1[index1];index1++;index3++;} for(index4=start1;index4<=end2;index4++) //copy the result array to//corresponding positions in the original array{array1[index4]=result[index4];}}void mergesort(int data[maxsize],int start,int end)//sorts elements from positions//start to end in an array using merge sort{int mid;if(start<end){mid=(start+end)/2;mergesort(data,start,mid); //first sort the first halfmergesort(data,mid+1,end);//now sort the remainingmerge(data,start,mid,end);//merge them}}void main(){//program to sort an array of 10 elements using merge sortint A[maxsize], final,i,result,n;printf("Enter the no. of elements\n");scanf("%d",&n);result=0;for(i=0;i<n;i++){printf("Give A[%d]:",i);scanf("%d",&A[i]);}mergesort(A,0,n-1);printf("\nThe sorted Array is\n");for(i=0;i<n;i++)printf("%d\n",A[i]);getch();

Page 62: Data Structures Made Simple

}Output of the ProgramEnter the no. of elements7Give A[0]:12Give A[1]:45Give A[2]:89Give A[3]:32Give A[4]:1Give A[5]:4Give A[6]:55

The sorted Array is141232455589

4.12. Bucket Sort

Bucket Sort is another approach based on comparing digits. Bucket sort assumes that the range ofinput is known beforehand .It assumes that the input is uniformly distributed over the range. Inthis method the range of input is divided in to sub intervals called Buckets and place the inputinto these buckets. Then these buckets are sorted and listed in order.

Program for Bucket Sort Program 4.6 #include <stdio.h> void bucketSort(int array[],int n); int main() { int array [10] = {1,7,4,6,4,2,8,1,2,9};

Page 63: Data Structures Made Simple

int n = 10; int i; printf("The array is\n\n"); for (i = 0;i < n;i++) printf("%d ", array [i]); printf("\n"); bucketSort(array, n); printf("The Sorted array is\n\n"); for (i = 0;i < n;i++) { printf("%d ", array [i]); } printf("\n"); getch(); return 0; }

void bucketSort(int array [], int n) { int i, j; int a[n]; for(i=0;i<n;i++) { a[i] = 0; }

for(i=0;i<n;i++) { (a[array [i]])++; } for(i=0,j=0;i<n;i++) { for(;a[i]>0;(a[i])--) { array [j++] = i; }

Page 64: Data Structures Made Simple

} }

Output of the Program The array is 1 7 4 6 4 2 8 1 2 9 The Sorted array is 1 1 2 2 4 4 6 7 8 9

4.13. Heap Sort Heap sort uses a heap for sorting. A heap is a type of binary tree. It has two properties. 1. It is a complete binary tree. At each level, except possibly the last level, every node has two

children. 2. The value of each node is, greater than or equal to the values of nodes in the children. (This is

called the heap property) Algorithm for heap sort contains the following steps: 1. Construct a heap from the array elements. 2. Shift the root element of the heap to the end of the array, and then rebuild the heap structure

with the remaining elements. 3. Repeat step 2 until there are no more elements in the heap. The time complexity of heap sort is O(nlogn).

Figure for heap Program for HeapSort Program 4.7 #include<stdio.h> #include<conio.h>

Page 65: Data Structures Made Simple

void heapsorting(int [ ],int); void main() { int w[25],i,n; printf("Enter the no of elements to sort\n" ); scanf("%d",&n); printf("Enter %d elements to sort\n",n); for(i=0;i<n;i++ ) scanf("%d",&w[i]); heapsorting(w,n); printf("\nAfter the heap sort\n"); for(i=0;i<n;i++) printf("\t%d",w[i]); getch(); } void heapsorting(int x[ ],int n) { int i,el, s1,f1,evalue; for(i=1;i<n;i++) { el=x[i]; s1=i; f1=(s1-1)/2; while(s1>0&&x[f1]<el) { x[s1]=x[f1]; s1=f1; f1=(s1-1)/2; } x[s1]=el; } for(i=n-1;i>0;i--) { evalue=x[i]; x[i]=x[0]; f1=0; if(i==1) s1= -1;

Page 66: Data Structures Made Simple

else s1=1; if(i>2&&x[2]>x[1]) s1=2; while(s1>=0&& evalue<x[s1]) { x[f1]=x[s1]; f1=s1; s1=2*f1+1; if(s1+1<=i-1&&x[s1]<x[s1+1]) s1=s1+1; if(s1>i-1) s1= -1; } x[f1]=evalue; } } Output of the Program Enter the no of elements to sort 7 Enter 7 elements to sort 99 77 33 55 88 22 44

After the heap sort 22 33 44 55 77 88 99

4.18 Compare Different Sorting Algorithms

We have seen different sorting and searching algorithms. Depending up on the types of data and theoperation one may perform on data, we are choosing different sorting algorithm. We compare algorithms based on time complexity .The time complexity of algorithm measures therunning time of the algorithm compared to the input data.

Page 67: Data Structures Made Simple

Time complexity is represented using the O notation. An algorithm is O(n) if the running time is lessthan or equal to a constant times n. Here n is the size of the input. Similarly an algorithm is O (n2) ifit’s running time less than or equal to a constant time n2, and so on. And O(n) algorithm is consideredbetter than O (nlogn) algorithm, which in turn is consider better than an O(n2) algorithm and so on. We can see the time complexity for different algorithms

Algorithm

Worst case

Average case

Bubble sort

O(n2)

O(n2)

Insertion sort

O(n2)

O(n2)

Selection sort

O(n2)

O(n2)

Merge sort

O(n log n)

O(n log n)

Quick sort

O(n2)

O(n log n)

Heap sort

O( n log n)

O(n log n)

From the above comparison it is clear that 1. Bubble sort, selection sort and insertion sort have the same time complexity O(n2). Also

bubble sort is easy to implement, But is highly inefficient. 2. Quick sort and heap sort have the same average time complexity O(nlogn). So both of them

are considered better than Bubble sort, selection sort or insertion sort. The choice of thecorrect pivot point is important in quick sort, But heap sort guarantees O(nlogn) performanceunder any condition.

3. Merge sort also works in O(nlogn) time, so it is better than Bubble sort, selection sort orinsertion sort ,but it works only when the given lists are already sorted.

4. Bucket sort is an O(n) sorting algorithm, So it can be considered better than other algorithms,but it works only when the numbers are uniformly distributed and range of input known inadvance.

5. For smaller input simpler algorithms such as bubble sort may be better, but for larger inputalgorithms like Quick sort and heap sort are better. Also if the input consists of two sortedlists, merge sort is better. If the input is uniformly distributed and ranges of values are knownin advance, bucket sort is better.

4.14 Searching

Page 68: Data Structures Made Simple

Searching is the process of determining whether a given element is in a list. A search technique willgive the position of the element if one is found. Otherwise it will say that element is not found.

4.15. Linear search We also call it as sequential searching. In Linear search searching means a set of data for a particularvalue .We are the entire list one by one until we get the desired value. This is one of the simplestsearching Techniques. Advantage : Good to use for small sets of data. Disadvantage: Suppose the data set is too big, then the searching process will be slower.

Program for Linear search Program 4.8 #include <stdio.h>

void main(){int a[10],i,n,position,n1;printf("Enter the size of the array\n");scanf("%d",&n);printf("Enter the elements\n");for(i=0;i<n;i++)scanf("%d",&a[i]);printf("Enter the element to search\n");scanf("%d",&n1);for(i=0;i<n; i++){if(a[i]==n1){position=i;printf(" Search Successful :Location at %d", position);break;

Page 69: Data Structures Made Simple

}}if(i==n)printf(" Sorry search unsuccessful");getch();}Output of the ProgramEnter the size of the array7Enter the elements33772299554488Enter the element to search99Search Successfull:Location at 3

4.16 Binary Search

It is a technique to find out a particular value in a sorted list of items. Binary search is a fast andefficient searching technique. In binary search we are comparing the elements with the element in themiddle of the list(mid).we are taking the middle element by taking the first and last element of the list Mid= (beg+last) /2. A fast way to search a sorted array is to use a binary search. We are going to take the element in themiddle for seaching purpose. If the element we want to search is equal to mid element, the search isfinished. If the element is less than the mid element, we are searching on the first half. If it’s greater,we are searching at the second half. Advantage: Fast and easy to implement. Disadvantage: Works only on sorted array. Program 4.9Program for Binary search

Page 70: Data Structures Made Simple

#include<stdio.h>void main(){int array[10],i,j,t,begin,end,n,middest,num;printf("Enter the size of the array\n");scanf("%d",&n);printf("Enter the elements in sorted order\n");for(i=0;i<n;i++)scanf("%d",&array[i]);begin=0;end=n;printf("Enter the element to search\n");scanf("%d",&num);while(begin<end){middest=(begin+end)/2;if(array[middest]==num){printf("Search is success element found at location at %d",middest);break;}if(num>array[middest])begin=middest+1;elseend = middest-1;}if(begin==end)printf("unsuccessful search");getch();}

Output of the program

Enter the size of the array10Enter the elements in sorted order11 22 33 44 55 66 77 88 99 100Enter the element to search77Search is success element found at location at 6

Page 71: Data Structures Made Simple

4.17 Difference between Linear Search & Binary Search

5. We use linear search for a small set of values. But we can use Binary search for a large set ofvalues.

6. On comparing with binary search technique linear search is a slower one. 7. Binary search is applicable in the case of sorted elements only. But using linear search you

can find out the element from unsorted list. In the case of an unsorted array linear search is thebest one.

Page 72: Data Structures Made Simple

Exercises

1. Explain different sorting methods. 2. What is external sorting? 3. Define searching. 4. Compare different searching algorithms. 5. What is time complexity? 6. List out the complexity comparison of different sorting algorithms. 7. Explain quick sort. 8. Write a c program for linear search. 9 Write a c program to implement heap sort. 10. Write a c program to implement bubble sort.

Page 73: Data Structures Made Simple

Chapter V Stacks and Queues

5.1 Stack Stack is a data structure which uses the principle of Last in first out (LIFO). In stacks we areremoving the element that we recently added in to the list. The most recently added item is at the topof the stack. Here insertion and deletion is carried out at one end. Basic stack operations are push andpop. Insertion of elements in to the stack is known as PUSH operation and deletion of elements from stackis known as POP operation. Stack can represented using both an array and a linked list.

Figure 5.1

Different operations on a stack � Push : Places an object on the top of the stack � Pop : Removes an object from the top of the stack � Empty : Reports whether the stack is empty or not.

5.2 Implementation of Stack Using Arrays and pointers Array can be used to represent stacks. On using array limited number of elements can be inserted anddeleted. Suppose we have declared an array of stack of size 4 Eg int stack [5], and then we can insert maximum 5 elements, starting from stack [0] to stack [4]. Wehave a pointer Top which always point to the top element in the stack. Initially we have declared thattop as empty, by giving a value (-1).If stack contains single data item top points to stack [0]. When anew element is inserted in to the stacks, top is increments by one. The pointer is decremented by oneeach time a deletion happens.Also a stack can be implemented using pointers.

Page 74: Data Structures Made Simple

Program to implement stacks using arrays

Program 5.1

#include<stdio.h> #define Size 4 void pushoperation(); //add item to stack void popoperation(); //delete item from stack void showstack(); //to show stack int stack[Size],Top=-1; void main() { int option; do { printf("Which stack operation you want?\n"); printf("1-PUSH\n2-POP\n3-SHOW\n4.Exit\n"); scanf("%d",&option); switch(option) { case 1:pushoperation(); break; case 2:popoperation(); break; case 3:showstack(); break; } }while(option<4); getch(); }

void pushoperation() //add item to stack

Page 75: Data Structures Made Simple

{ int v; if(Top>=Size) printf(" Sorrry not enough space"); else { printf("Please enter the element in to the stack\n"); scanf("%d",&v); Top=Top+1; stack[Top]=v; } }

void popoperation() //delete item from stack

{ int t; if(Top==-1) { printf("Sorry stack is empty"); return; } else { t=stack[Top]; Top=Top-1; printf("%d popped from the stack\n",t); } }

void showstack() //to show stack

{ int i;

Page 76: Data Structures Made Simple

if (Top==-1) printf("Stack is empty "); else { printf("Stack contents are..\n"); for(i=Top;i>=0;i--) { printf("%d\n", stack[i]); } } } Output of the program Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 1 Please enter the element in to the stack 111 Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 1 Please enter the element in to the stack 222 Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 1 Please enter the element in to the stack 333 Which stack operation you want? 1-PUSH

Page 77: Data Structures Made Simple

2-POP 3-SHOW 4.Exit 3 Stack contents are.. 333 222 111 Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 2 333 popped from the stack Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 3 Stack contents are.. 222 111 Which stack operation you want? 1-PUSH 2-POP 3-SHOW 4.Exit 4

Program for implementing stack using pointers:

Program 5.2

Page 78: Data Structures Made Simple

#include<stdio.h> struct stack { int value; struct stack *link; }; struct stack *pushoperation(struct stack *top,int val); struct stack *popoperation(struct stack *top,int *val); void showstack(struct stack *top);

void main() { struct stack *top; int val,ch; top=NULL; do { printf("\n Menu for stack operation"); printf("\n 1.Add\n 2.Delete\n 3.Show\n"); printf("\nEnter u r choice\n"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the element to push in to stack\n"); scanf("%d",&val); top=pushoperation(top,val); break; case 2: top=popoperation(top,&val); if(top!=NULL) printf("the deleted value is %d",val); break; case 3: showstack(top); break; }

Page 79: Data Structures Made Simple

}while(ch<4); getch(); }

struct stack* pushoperation(struct stack *top,int val) // add item to stack { struct stack *w; w=(struct stack*)malloc (sizeof(struct stack)); w->value=val; w->link=top; top=w; return(top); } struct stack* popoperation(struct stack*top,int *val) // Remove item from stack { struct stack *w; if (top==NULL) { printf(" Sorry stack is empty\n"); top= NULL; } else { w=top; top=top->link; *val=w->value; } return(top); } void showstack(struct stack *top) //Display stack items { struct stack *p1; p1=top; printf("contents of stack is\n"); while(p1!=NULL) { printf("\n%d",p1->value); p1=p1->link;

Page 80: Data Structures Made Simple

} }

Output of the Program Menu for stack operation 1.Add 2.Delete 3.Show Enter u r choice 1 Enter the element to push in to stack 222 Menu for stack operation 1.Add 2.Delete 3.Show Enter u r choice 1 Enter the element to push in to stack 333 Menu for stack operation 1.Add 2.Delete 3.Show Enter u r choice 3 contents of stack is 333 222 Menu for stack operation 1.Add 2.Delete 3.Show Enter u r choice 2 the deleted value is 333 Menu for stack operation

Page 81: Data Structures Made Simple

1.Add 2.Delete 3.Show Enter u r choice 3 contents of stack is 222 Menu for stack operation 1.Add 2.Delete 3.Show Enter u r choice 4

5.3 Applications of Stacks

Stack is a very useful data structure which finds applications in a variety of areas. They include: � Evaluation of arithmetic Expression An arithmetic expression like A+B-C/2 consists of operators like +,-,*and operand which are

numeric values or variables like a, b , c in order to convert such an expression to instructionunderstandable by the computer one has to ,first determine the exact order in which theoperators are evaluated. Each operator is given a priority and the expression is evaluatedusing these priorities. In this evaluation we use the stack to store the different operators andoperands.

� Recursion: During recursion a function calls itself. The values of the variables in the calling function are

pushed in to a stack. They are popped out, when the called function returns. �n operating systems when a running process A (also called process) passes control to

another process B the details of the former process A is kept in the stack.

5.4 Queues

Page 82: Data Structures Made Simple

A queue is a linear data structure in which addition of new element takes place at one end called‘rear’. And deletion of existing elements takes place at another end called ‘front’.

A queue is often called as FIRST IN FIRST OUT (FIFO) structure.

Figure 5.2

Queue Implementation Using Array

Program 5.3

#include<stdio.h> #define size 5 // Size of the queue int front,rear; int queue[size]; int i,j; void show(); void insert(int); void delete(); void main() { int j,i,ch,v; front=-1; rear=-1; do {

Page 83: Data Structures Made Simple

printf("Select the Menu operation\n"); printf("\n1.InsertQueue\n2.DeleteQueue\n3.Show\n4.Quit\n"); printf("Enter your choice\n"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the value\t"); scanf("%d",&v); insert(v); break; case 2: delete(); break; case 3: show(); break; } }while(ch<4); getch(); }

void show() // Display Queue items { if (front==rear) { printf("Empty queue"); return; } if(front <rear) { printf("Elements in the queue are\n"); for(i=front+1;i<=rear;i++) { printf("%d\n",queue[i]); } }

Page 84: Data Structures Made Simple

} void insert(int item) //Add item to Queue { if(rear==(size-1)) { printf("Queue overflow"); return; } rear++; queue[rear]=item; }

void delete() //Remove item from Queue { int v; if(front==rear) printf("Queue is empty"); else { front=front+1; v=queue[front]; printf("Element deleted from q is %d\n",v); } }

Output of the program

Select the Menu operation 1.InsertQueue 2.DeleteQueue 3.Show 4.Quit Enter your choice 1 Enter the value 22 Select the Menu operation

Page 85: Data Structures Made Simple

1.InsertQueue 2.DeleteQueue 3.Show 4.Quit Enter your choice 1 Enter the value 55 Select the Menu operation 1.InsertQueue 2.DeleteQueue 3.Show 4.Quit Enter your choice 3 Elements in the queue are 22 55 Select the Menu operation 1.InsertQueue 2.DeleteQueue 3.Show 4.Quit Enter your choice 2 Element deleted from q is 22 Select the Menu operation 1.InsertQueue 2.DeleteQueue 3.Show 4.Quit Enter your choice 3 Elements in the queue are 55 Select the Menu operation 1.InsertQueue 2.DeleteQueue 3.Show

Page 86: Data Structures Made Simple

4.Quit Enter your choice 4

Queue implementation using pointers Program 5.4

#include<stdio.h> struct queue { int v1; struct queue *link; }; struct queue * addqueue(struct queue *rear,int val); struct queue * deletequeue(struct queue *front ,int *val); void showqueue(struct queue *front);

void main() { struct queue *front,*rear; int val,ch; front=rear=NULL; do { printf("\n Menu for queue operation"); printf("\n 1.Add\n 2.Delete\n 3.Show\n 4.Exit"); printf("\nEnter u r choice\n"); scanf("%d",&ch); switch(ch) {

Page 87: Data Structures Made Simple

case 1: printf("Enter the value to be added\n"); scanf("%d",&val); rear=addqueue(rear,val); if(front==NULL) front=rear; break; case 2: front=deletequeue(front,&val); if(val!=-1) printf("The deleted value is %d",val); if(front==NULL) rear=front; break; case 3: showqueue(front); break; } }while(ch<4); getch(); } struct queue *addqueue(struct queue *rear,int val) //Add item to Queue { struct queue *w; w=(struct queue *)malloc (sizeof(struct queue)); w->v1=val; w->link=NULL; if(rear!=NULL) rear->link=w; rear=w; return(rear); } struct queue *deletequeue(struct queue *front ,int *val) //Remove item { struct queue *w; if(front==NULL) { printf("\n Sorry Queue is empty"); *val=-1;

Page 88: Data Structures Made Simple

} else { w=front; front=front->link; *val=w->v1; } return front; } void showqueue(struct queue *front) // Display Queue items { struct queue *p; p=front; printf("\nThe contents of queue is\n"); while(p!=NULL) { printf("%d",p->v1); p=p->link; } }

Output of the Program

Menu for queue operation 1.Add 2.Delete 3.Show 4.Exit Enter u r choice 1 Enter the value to be added 222

Menu for queue operation 1.Add 2.Delete

Page 89: Data Structures Made Simple

3.Show 4.Exit Enter u r choice 1 Enter the value to be added 555

Menu for queue operation 1.Add 2.Delete 3.Show 4.Exit Enter u r choice 3

The contents of queue is 222555 Menu for queue operation 1.Add 2.Delete 3.Show 4.Exit Enter u r choice 2 The deleted value is 222 Menu for queue operation 1.Add 2.Delete 3.Show 4.Exit Enter u r choice 3

The contents of queue is 555 Menu for queue operation

Page 90: Data Structures Made Simple

1.Add 2.Delete 3.Show 4.Exit Enter u r choice 4

5.5 Circular Queue In circular queue the elements are represented in a circular fashion like this cq[0],cq[1],cq[2],…….cq[n-1].with cq[0] following cq[n-1]. In circular queue insertion of the element is done at thevery first location of the queue if the last location of the queue is full.

Figure 5.3 Circular Queue implementation 5.5 Program

#include<stdio.h> #include<conio.h> void addcirqueue (int cq [],int*rear,int val,int *front); int deletecirqueue(int cq [],int *front,int *rear); void showcirqueue(int cq [],int *front,int *rear); int n;

Page 91: Data Structures Made Simple

void main() { int cq [35]; int ch,front,rear,val; printf("Enter the size of the circular queue\n"); scanf("%d",&n); front=rear=0; do { printf("\nMenu for circular queue operation"); printf("\n 1.Add\n 2.Delete\n 3.Show\n"); printf("\nEnter u r choice\n"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the value to be added\n"); scanf("%d",&val); addcirqueue(cq,&rear,val,&front); break; case 2: val=deletecirqueue(cq,&front,&rear); if(val!=0) printf("The deleted value is %d",val); break; case 3: showcirqueue(cq,&front,&rear); break; } }while(ch<4); getch(); } void addcirqueue (int cq[],int*rear,int val,int *front) { if((*rear+1)%n==*front) { printf("Queue is full");

Page 92: Data Structures Made Simple

} else { *rear=(*rear+1)%n; cq[*rear]=val; } } int deletecirqueue(int cq[],int *front,int *rear) { int v1; if(*front!=*rear) { *front=(*front+1)%n; v1=cq[*front]; return v1; } else { printf("Queue is empty"); return 0; } } void showcirqueue(int cq[],int *front,int *rear) { int j; j=*front; printf("Contents"); while(j!=*rear) { j=(j+1)%n; printf("\n%d",cq[j]); } }

Ouput of the program

Page 93: Data Structures Made Simple

Enter the size of the circular queue 5

Menu for circular queue operation 1.Add 2.Delete 3.Show

Enter u r choice 1 Enter the value to be added 222

Menu for circular queue operation 1.Add 2.Delete 3.Show

Enter u r choice 1 Enter the value to be added 444 Menu for circular queue operation 1.Add 2.Delete 3.Show Enter u r choice 3 Contents 222 444 Menu for circular queue operation 1.Add 2.Delete 3.Show

Page 94: Data Structures Made Simple

Enter u r choice 2 The deleted value is 222 Menu for circular queue operation 1.Add 2.Delete 3.Show

Enter u r choice 3 Contents 444 Menu for circular queue operation 1.Add 2.Delete 3.Show

Enter u r choice 4

5.6 Priority queue

Priority queue is another type of data structure in which each element is having a priority andelements having same priority form a separate queue. Thus a priority queue is equivalent to a queue ofmultiple queues, where elements having higher priority are processed before elements having lowerpriority.

Conceptual view of a priority queue

Page 95: Data Structures Made Simple

Figure 5.4

Implementation view

Figure 5.5

Program for priority Queue using linked list: 5.6 Program #include <stdio.h> struct node //The node with one data field one priority field and twp pointers { int data,priority; struct node *rightlink; struct node *leftlink; }; struct node *front,*rear,*list,*ptr,*new,*ptr1,*ptr2,*headptr,head,node1,node2; void insert(int item,int priority); // inserts a given item with a given

Page 96: Data Structures Made Simple

//priority to the queue int delete(int priority); /*checks whether an item with a given priority exists.If so it is removed */ void show();

void main() { int option,item1,priority; headptr=(struct node*)malloc(sizeof(struct node));//a pointer to head node head =*headptr; (*headptr).leftlink=NULL; (*headptr).rightlink=NULL; (*headptr).data=0; (*headptr).priority=-99; do { printf("\n 1)Add 2)Delete 3)Show 4)Exit\n"); scanf("%d",&option); switch(option) { case 1: printf("\nEnter the value to insert:\t"); scanf("%d",&item1); printf("\nenter the priority:\t"); scanf("%d",&priority); insert( item1, priority); break; case 2: printf("\nEnter the priority value to delete: "); scanf("%d",&priority); item1= delete( priority); break; case 3: show(); break;

Page 97: Data Structures Made Simple

} } while(option!=4); getch(); } void insert(int item ,int p) { ptr=headptr; new =(struct node*)malloc(sizeof(struct node)); (*new).data=item; (*new).priority=p; while(((*ptr).rightlink!=NULL)&&((*ptr).priority<p))/*scan through the list until we reach the end or an item with higher priority*/ { ptr=(*ptr).rightlink; } if( (ptr==headptr) ||((*ptr).rightlink==NULL)&&((*ptr).priority<p)) /*end of the list. insert the item at the last */ { (*ptr).rightlink=new; //printf("data %d,priority %d",(*ptr).data,(*ptr).priority); (*new).leftlink=ptr; (*new).rightlink=NULL; rear=new; } else //insert the item before the item with higher priority if((*ptr).priority>=p) { ptr1=(*ptr).leftlink; (*ptr1).rightlink=new; (*new).rightlink=ptr; (*ptr).leftlink=new;

Page 98: Data Structures Made Simple

(*new).leftlink=ptr1; } front=headptr; } int delete(int p) { if(rear==NULL) { printf("\n queue is empty\n"); return(1); } else { ptr=rear; while( ((*ptr).priority>p)&&(ptr!=headptr)) { ptr=(*ptr).leftlink; } if((ptr==headptr)||(*ptr).priority<p) { printf("no item with that priority"); return(1); } else if((*ptr).priority==p) { ptr1=(*ptr).leftlink; ptr2=(*ptr).rightlink; if(ptr==rear) { rear=ptr1; (*ptr1).rightlink=NULL; } else { (*ptr1).rightlink=ptr2; (*ptr2).leftlink=ptr1;

Page 99: Data Structures Made Simple

} } } return((*ptr).data); }

void show() { if((*headptr).rightlink==NULL) { printf("the queue is empty"); return; } ptr1= (*headptr).rightlink; while(ptr1!=NULL) { printf("DATA: %d Priority %d\n",(*ptr1).data,(*ptr1).priority ); ptr1=(*ptr1).rightlink; }; }

Output of the Program 1)Add 2)Delete 3)Show 4)Exit 1 Enter the value to insert: 333 enter the priority: 2 1)Add 2)Delete 3)Show 4)Exit 1 Enter the value to insert: 777 enter the priority: 1 1)Add 2)Delete 3)Show 4)Exit 3 DATA: 777 Priority 1 DATA: 333 Priority 2 1)Add 2)Delete 3)Show 4)Exit

Page 100: Data Structures Made Simple

2 Enter the priority value to delete: 1 1)Add 2)Delete 3)Show 4)Exit 3 DATA: 333 Priority 2 1)Add 2)Delete 3)Show 4)Exit 4 5.7 Dequeue

Another data structure similar to queue, but operation such as insertion and deletion is made to orfrom both end of the queue. But insertion and deletion is not possible at the middle of the queue.There are two types of dequeue 1. Input restricted dequeue 2. Output restricted dequeue 5.8. Input Restricted Dequeue

This allows insertion only at one end of the array or list, but deletion allowed at both ends. 5.9 Output Restricted Dequeue This allows insertion at both ends of the list but deletion allowed at only one end of the array.

DEQUEUE Figure 5.5 Sample program for Dequeue 5.7 Program

Page 101: Data Structures Made Simple

#include<stdio.h> #define maxsize 30 int left,right; int dequeue[maxsize]; int i,j; void insertright(int item) // insert element to the right { if( ( (left==0)&&(right==(maxsize-1)))) { printf("queue is full"); return; } else if( left==-1)//empty queue { left++; right++; } else if(right==maxsize-1) right=0; else right++; dequeue[right]= item; } void show() // Displays the dequeue { int front=left; int rear =right; if (left== -1) { printf("empty queue"); return; } if(left <right) for(i=front;i<=rear;i++) printf("%d ",dequeue[i]); else { for(i=front;i <=maxsize-1;i++)

Page 102: Data Structures Made Simple

printf("%d ",dequeue[i]); for(i=0;i<=right;i++) printf("%d ",dequeue[i]); } printf("\n"); } void insertleft(int item) // Insert element to the left { if((left==0&&right==(maxsize-1))||(left==right+1)) { printf("\nq overflow"); return; } if(left==-1) { left++; right++; } else { if(left==0) left=maxsize-1; else left=left-1; dequeue[left]=item; } } void deleteleft() // Delete element from left { if(left==-1) { printf("\nqueue underflow"); return; } printf("element deleted from q is%d\n",dequeue[left]); if(left==right) { left=-1;

Page 103: Data Structures Made Simple

right=-1; } else if(left==maxsize-1) left=0; else left=left+1; } void deleteright() //Delete element from right { if(left==-1) { printf("queue underflow"); return; } printf("element deleted from q is%d\n ",dequeue[right]); if(left==right) { left=-1; right=-1; } else if(right==0) right=maxsize-1; else right=right-1; } void main() { int j,i,ch,v; left=-1; right=-1; do { printf("Select the Menu operation\n"); printf("\n1.InsertRight\n2.InsertLeft\n3.DeleteRight\n"); printf("4.DeleteLeft\n5.Show\n6.Quit\n"); printf("\nEnter your choice\n");

Page 104: Data Structures Made Simple

scanf("%d",&ch); switch(ch) { case 1: printf("Enter the value "); scanf("%d",&v); insertright(v); break; case 2: printf("Enter the value "); scanf("%d",&v); insertleft(v); break; case 3: deleteright(); break; case 4: deleteleft(); break; case 5: show(); break; } }while(ch<6); getch(); }

Output of the Program Select the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice

Page 105: Data Structures Made Simple

1 Enter the value 222 Select the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice 2 Enter the value 888 Select the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice 5 888 222 Select the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit

Enter your choice 3 element deleted from q is222 Select the Menu operation 1.InsertRight 2.InsertLeft

Page 106: Data Structures Made Simple

3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice 4 element deleted from q is888 Select the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice 5 empty queueSelect the Menu operation 1.InsertRight 2.InsertLeft 3.DeleteRight 4.DeleteLeft 5.Show 6.Quit Enter your choice 6

5.10 Applications of Queues

7. We can use queues in Time sharing systems. 8. We can use queues in computer networks. 9. Queues are used in simulation. 10. In computer systems communication between two process or two programs or two systems is

done by sending messages. For this there must be a “holding area” for messages between twoprocesses, two programs, or even two systems. This holding area is usually called a “buffer”and is often implemented as a queue.

11. Operating systems often maintain a queue of processes that are ready to execute or that are

Page 107: Data Structures Made Simple

waiting for a particular event to occur.

Exercises

Page 108: Data Structures Made Simple

11.2. Define stack 11.3. Explain push and pop operations in the stack 11.4. Write a c Program to implement a stack using an array 11.5. List out the applications of Stack 11.6. Define Queue 11.7. List Applications of queues 11.8. Write a C program to implement queue using Array 11.9. Implement a circular queue 11.10. What is a priority queue? 11.11. What are dequeues? 11.12. Implement a dequeue

Page 109: Data Structures Made Simple

Chapter Vl Linked List

6.1 Linked list

A linked list is a data structure. Linked list is a linear list of nodes, each containing data area andone or two pointers (“links”) pointing to the next coming or previous nodes. Advantage of linked list over array is that we do not need to mention the size of the elements in linkedlist application Using linked list we can insert and delete nodes from any point in the list. But linkedlist never allow doing random access of nodes. Several different types of linked list exist: singly-linked lists, doubly-linked lists, circularly-linkedlist and circular doubly linked lists. The following fig is an example for single Linked list.

Figure 6.1 linked list

6.2Creation of Linked List

We can insert and delete items in a linked list when it is necessary. The nodes of a linked list

are written as structures. We use some memory location to store the nodes (structure variable).Thislocation is accessed by means of pointers. The “struct” declaration does not allocate storage, but itdescribes the format of the nodes. Storage space of a node is created by the dynamic memoryallocation function malloc.Here Pnode points to the structure variable node. Initially pointer points to the first node. Creation oflinked list contains the following steps.

Page 110: Data Structures Made Simple

11. First we check that pnode1==NULL, if so we dynamically allocate memory for the pnode1(first node).make pnode’s link as NULL. Assign pnode as the first node.12. If pnode1! =NULL, then we are allocating memory for the next node (pnode1�link). 6.3 Inserting Node Insertion of nodes in a linked list mainly carried out by three ways.12. Insertion at first position: This is done by adding a new node and set its pointer to the currentstart. Start will be set to point to the list. 2. Insertion at the end section: This is done by adding a new node at the end point of the list.3. Insertion in specified position: We need to mention the position of insertion. For that we aresearching the entire list and insert the node at the right position.

Figure 6.2 Inserting a node

6.4 Deletion of nodes

We are deleting a node from the linked list by mentioning its data .And we are searching the

entire linked list for the data, until we get it. Then we use free function to delete the node.

123

333

444

123

Page 111: Data Structures Made Simple

333

444

Figure 6.3 Deleting a node

Program for linked list operations Program 6.1

#include<stdio.h> struct node1 { int value; struct node1 *link; }; struct node1 *pnode1,*first,*x,*t,*w;

void main() { int ch; void addList(); void deleteList(); void displayList(); pnode1=NULL; while(ch!=4) { printf("\nLinked list operation menu"); printf("\n1.Add\n2.Delete\n3.Display\n4.Exit\n"); printf("Enter u r choice\t"); scanf("%d",&ch); switch(ch) {

Page 112: Data Structures Made Simple

case 1: addList(); break; case 2: deleteList(); break; case 3: displayList(); break; } } getch(); }

void addList() //Add elements to list { int v; printf("Enter the value of the element\t"); scanf("%d",&v); if (pnode1==NULL) { pnode1=malloc(sizeof(struct node1)); pnode1->value=v; pnode1->link=NULL; first=pnode1; } else { pnode1->link=(struct node1*) malloc(sizeof(struct node1)); pnode1->link->value=v; pnode1=pnode1->link; } pnode1->link=NULL; }

Page 113: Data Structures Made Simple

void displayList() //Display elements in the List { printf("\n\n"); pnode1=first; while(pnode1!=NULL) { printf("%d->",pnode1->value); pnode1=pnode1->link; } printf("NULL"); }

void deleteList() //Display list elements { int v; printf("enter the value to delete"); scanf("%d",&v); pnode1=first; t=NULL; while(pnode1!=NULL&&pnode1->value!=v) { t=pnode1; pnode1=pnode1->link; } if(pnode1!=NULL) { if(t==NULL) first=first->link; else t->link=pnode1->link; free(pnode1); printf("Node Deleted"); } else { printf("Node with the given value not exit");

Page 114: Data Structures Made Simple

} } Output of the Program

Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit Enter u r choice 1 Enter the value of the element 222

Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit Enter u r choice 1 Enter the value of the element 111

Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit Enter u r choice 3

222->111->NULL Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit

Page 115: Data Structures Made Simple

Enter u r choice 2 enter the value to delete111 Node Deleted Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit Enter u r choice 3

222->NULL Linked list operation menu 1.Add 2.Delete 3.Display 4.Exit Enter u r choice 4

6.5 Doubly-linked List Another type of linked list is a doubly-linked list or two-way linked list. Each node has two links:one points to the previous node, or points to a null value and one points to the next, or points to a nullvalue .Here a node is divided into three parts, where three fields of information are stored. � Leftlink: Holds the address of previous node. � Data field: Holds the data item. � Right link: Holds the address of the next node. The following figure for doubly linked list.

Page 116: Data Structures Made Simple

Figure 6.4 Doubly linked list

6.6 Operations on a doubly linked list

Using a doubly Linked List we can traverse both sides. Main operations of doubly Linked list arelisted below.

3. creation2. Insertion3. Deletion4. TraversalHere pnode1 (first node) has two links that are rlink and llink. Initially creating the first node indoubly linked list we are setting the first and last pointers points to that node. Again we arecreating an another node, then last pointer points to the newly created node (t).Insertion anddeletion operations are similar to the linear linked list.

A Sample program for Doubly Linked List Program 6.2

#include<stdio.h> struct dlinklist { int no; struct dlinklist *rlink,*llink; }; struct dlinklist *pnode1,*first,*t,*last,*temp; void main() { void adddlist(); void viewdlist(); void insertNode(); void deleteNode(); int ch; pnode1=NULL; do { printf("\n Doubly Linked list operation menu"); printf("\n1.Add\n2.View\n3.InsertNode\n4.DeleteNode\n5.Exit\n"); printf("Enter u r choice\n");

Page 117: Data Structures Made Simple

scanf("%d",&ch); switch(ch) { case 1: adddlist(); break; case 2: viewdlist(); break; case 3: insertNode(); break; case 4: deleteNode(); break; } }while(ch<5); getch(); } void adddlist() //Add Elements to doubly linked list { if (pnode1==NULL) { pnode1=(struct dlinklist*)malloc(sizeof(struct dlinklist)); printf("\nEnter the value of the element "); scanf("%d",&pnode1->no); pnode1->llink=NULL; pnode1->rlink=NULL; first=pnode1; last=pnode1; } else { t=(struct dlinklist*) malloc(sizeof(struct dlinklist)); printf("\nEnter the value of the element "); scanf("%d",&t->no); t->rlink=NULL; t->llink=pnode1;

Page 118: Data Structures Made Simple

pnode1->rlink=t; pnode1=pnode1->rlink; last=t; } } void viewdlist() // Display Elements of the list { printf("Enter the element from left to right\n"); temp=first; printf("NULL->"); while(temp!=NULL) { printf("%d->",temp->no); temp=temp->rlink; } printf("NULL\n"); printf("Enter the element from l right to left\n"); temp=last; printf("NULL->"); while(temp!=NULL) { printf("%d->",temp->no); temp=temp->llink; } printf("NULL"); } void insertNode() // Insert an element after another element { int val; struct dlinklist *newnode; printf("Enter after the value:"); scanf("%d",&val); temp=first; while(temp->no!=val) { temp=temp->rlink; if(temp==NULL)

Page 119: Data Structures Made Simple

{ printf("Value not found"); return; } } if(temp->no==val) { newnode=(struct dlinklist*) malloc(sizeof(struct dlinklist)); printf("\n Enter the value to insert "); scanf("%d",&newnode->no); newnode->rlink=temp->rlink; temp->rlink=newnode; newnode->llink=temp; newnode->rlink->llink=newnode; } } void deleteNode() //Delete element from the list { int val; printf("Enter the value to delete "); scanf("%d",&val); if(first->no==val) { first=first->rlink; first->llink=NULL; } else { temp=first; while(temp!=NULL&&temp->rlink->no!=val) temp=temp->rlink; if(temp==NULL) { printf("value not found in the list"); } temp->rlink=temp->rlink->rlink; temp->rlink->llink=temp; }

Page 120: Data Structures Made Simple

}

Output of the Program Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 1 Enter the value of the element 333 Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 1 Enter the value of the element 555 Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 2 Enter the element from left to right NULL->333->555->NULL Enter the element from l right to left NULL->555->333->NULL Doubly Linked list operation menu 1.Add

Page 121: Data Structures Made Simple

2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 3 Enter after the value:333 Enter the value to insert 444 Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 2 Enter the element from left to right NULL->333->444->555->NULL Enter the element from l right to left NULL->555->444->333->NULL Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 4 Enter the value to delete 444 Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 2 Enter the element from left to right

Page 122: Data Structures Made Simple

NULL->333->555->NULL Enter the element from l right to left NULL->555->333->NULL Doubly Linked list operation menu 1.Add 2.View 3.InsertNode 4.DeleteNode 5.Exit Enter u r choice 5

6.7 Circular Linked List

Circular linked list is similar to singly linked list. In the last node of the circular linked list we arestoring the address of the first node. So we can directly go to the first node from last node

Advantage: Back traversal is possible in circular linked list. Disadvantage: In circular linked list there is a probability for an infinite loop.

Figure 6.5 circular linked list

Program for Circular Linked List:

Page 123: Data Structures Made Simple

Program 6.3 #include <stdio.h> #include <malloc.h> struct circularlink { int info; struct circularlink *next; }; struct circularlink *lastnode; void makeList(int); void deleteNode(int); void showList(); void insertFirst(int); void insertAfter(int,int); void main() { int option; int n,value,position,i; lastnode=NULL; do { printf("1.MakeList\n"); printf("2.Insert First\n"); printf("3.Insert After \n"); printf("4.Delete\n"); printf("5.ShowList\n"); printf("6.Quit\n"); printf("Enter your choice : "); scanf("%d",&option); switch(option) { case 1: printf("Enter the number of nodes "); scanf("%d",&n); for(i=0; i < n;i++) {

Page 124: Data Structures Made Simple

scanf("%d",&value); makeList(value); } break; case 2: printf("Enter the element : "); scanf("%d",&value); insertFirst(value); break; case 3: printf("Enter the element : "); scanf("%d",&value); printf("Enter the position after which this element is inserted : "); scanf("%d",&position); insertAfter(value,position); break; case 4: if(lastnode == NULL) { printf("List underflow\n"); continue; } printf("Enter the number for deletion : "); scanf("%d",&value); deleteNode(value); break; case 5: showList(); break; }/*End of switch*/ }while(option<6);/*End of while*/ getch(); }/*End of main()*/ void makeList(int num) // Creating a list {

Page 125: Data Structures Made Simple

struct circularlink *q,*tmp; tmp= malloc(sizeof(struct circularlink)); tmp->info = num; if(lastnode == NULL) { lastnode = tmp; tmp->next = lastnode; } else { tmp->next = lastnode->next; /*added at the end of list*/ lastnode->next = tmp; lastnode = tmp; } }/*End of makeList()*/ void insertFirst(int num) // Insert element at first position { struct circularlink *tmp; tmp = malloc(sizeof(struct circularlink)); tmp->info = num; tmp->next = lastnode->next; lastnode->next = tmp; }/*End of insertFirst()*/ void insertAfter(int num,int pos) // Insert element after a position { struct circularlink *tmp,*q; int i; q = lastnode->next; for(i=0; i < pos-1; i++) { q = q->next; if(q == lastnode->next) { printf("There are less than %d elements\n",pos);

Page 126: Data Structures Made Simple

return; } }/*End of for*/ tmp = malloc(sizeof(struct circularlink) ); tmp->next = q->next; tmp->info = num; q->next = tmp; if(q==lastnode) /*Element inserted at the end*/ lastnode=tmp; }/*End of insertAfter()*/ void deleteNode(int num) //Delete a particular node { struct circularlink *tmp,*q; if( lastnode->next == lastnode && lastnode->info == num) /*Only one element*/ { tmp = lastnode; lastnode = NULL; free(tmp); return; } q = lastnode->next; if(q->info == num) { tmp = q; lastnode->next = q->next; free(tmp); return; } while(q->next != lastnode) { if(q->next->info == num) { tmp = q->next; q->next = tmp->next; free(tmp); printf("%d deleted\n",num); return;

Page 127: Data Structures Made Simple

} q = q->next; }/*End of while*/ if(q->next->info == num) { tmp = q->next; q->next = lastnode->next; free(tmp); lastnode = q; return; } printf("Element %d not found\n",num); }/*End of deleteNode()*/ void showList() // Display elements { struct circularlink *q; if(lastnode == NULL) { printf("List is empty\n"); return; } q = lastnode->next; printf("List is :\n"); while(q != lastnode) { printf("%d ", q->info); q = q->next; } printf("%d\n",lastnode->info); }/*End of showList()*/

Output of the Program 1.MakeList 2.Insert First 3.Insert After 4.Delete

Page 128: Data Structures Made Simple

5.Show List 6.Quit Enter your choice : 1 Enter the number of nodes 4 11 33 44 55 1.MakeList 2.Insert First 3.Insert After 4.Delete 5.Show List 6.Quit Enter your choice : 3 Enter the element : 22 Enter the position after which this element is inserted : 1 1.MakeList 2. Insert First 3.Insert After 4.Delete 5.Show List 6.Quit Enter your choice : 5 List is : 11 22 33 44 55 1.MakeList 2.Insert First 3.Insert After 4.Delete 5. Show List 6.Quit Enter your choice : 4 Enter the number for deletion : 22 22 deleted 1.MakeList 2.Insert First 3.Insert After 4.Delete 5.Show List 6.Quit

Page 129: Data Structures Made Simple

Enter your choice : 5 List is : 11 33 44 55 1.MakeList 2.Insert First 3.Insert After 4.Delete 5.Show List 6.Quit Enter your choice : 6

6.8 Circular Doubly-linked List Circular doubly linked list is a doubly linked list in which the last node of the list has its next pointerpointing to the first node, and the previous pointer of the first node points to the last node. In a circular doubly linked list we can be traverse clockwise or anticlockwise manner. In this list allnodes are linked as shown in the below figure. The only difference between double linked list andcircular double linked list is that here last node points to first node and first node points to last node.But in doubly linked list last node points to the NULL value.

Figure (6.5) circular doubly linked list

A Sample program for Circular doubly linked list 6.4 Program

#include<stdio.h> #include<conio.h> struct cirdl {

Page 130: Data Structures Made Simple

int v; struct cirdl *r,*l; }; void addcirdl(); void printltor(); void printrtol(); void deletecird1(); struct cirdl *head,*pnode1,*t; int ch; void main() { head=(struct cirdl*)malloc(sizeof(struct cirdl)); head->r=head; head->l=head; pnode1=head; do { printf("\nCircular Doubly Linked list operation menu\n"); printf("1.Add\n2.PrintFromleft\n3.PrintFromRight\n4.Delete\n5.Exit"); printf("\nEnter u r choice\t"); scanf("%d",&ch); switch(ch) { case 1: addcirdl(); break; case 2: printltor (); break; case 3: printrtol(); break; case 4: deletecird1(); break;

Page 131: Data Structures Made Simple

} }while(ch<5); getch(); }

void addcirdl() // Add Elements to list { if(pnode1==head) { pnode1=(struct cirdl*)malloc(sizeof(struct cirdl)); printf("\nEnter the value to insert\t"); scanf("%d",&pnode1->v); pnode1->l=head; pnode1->r=head; head->r=pnode1; head->l=pnode1; } else { t =(struct cirdl*)malloc(sizeof(struct cirdl)); printf("\nEnter the value to insert\t"); scanf("%d",&t->v); t->l=pnode1; pnode1->r=t; t->r=head; head->l=t; pnode1=pnode1->r; } }

void printltor() // Print elements from left to right { pnode1=head->r; while(pnode1!=head->l) { printf("%d->",pnode1->v); pnode1=pnode1->r;

Page 132: Data Structures Made Simple

} printf("%d",pnode1->v);

}

void deletecird1() // Delete a particular element { int v; printf("Enter the value to delete\t"); scanf("%d",&v); pnode1=head->r; if(v==pnode1->v) { head->r=pnode1->r; pnode1->r=head; } else { while(v!=pnode1->r->v&&pnode1!=head->l) pnode1=pnode1->r; pnode1->r=pnode1->r->r; pnode1->r->l=pnode1; } if(pnode1==head->l) { printf(" Sorry no such nodes exits"); } }

void printrtol() // Print Elements from eight to left { pnode1=head->l; while(pnode1!=head->r) { printf("%d->",pnode1->v);

Page 133: Data Structures Made Simple

pnode1=pnode1->l; } printf("%d",pnode1->v); }

Output of the Program

Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 1 Enter the value to insert 12 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 1 Enter the value to insert 14 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 1 Enter the value to insert 16 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete

Page 134: Data Structures Made Simple

5.Exit Enter u r choice 2 12->14->16 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 3 16->14->12 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 4 Enter the value to delete 14 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 2 12->16 Circular Doubly Linked list operation menu 1.Add 2.PrintFromleft 3.PrintFromRight 4.Delete 5.Exit Enter u r choice 5

6.9Advantages/Disadvantages of Linked Lists

Page 135: Data Structures Made Simple

Advantage

4. Linked lists use dynamic memory allocation. This makes efficient use of main memory.5. Insertion and deletion of nodes arbitrary positions is easy. For insertion and deletion we needto just adjust the pointers.6. We can move both directions using doubly linked list.7. Linked lists do not require continuous memory blocks for allocation.8. Linked list can grow and shrink according to user requiements

Disadvantage:

8. We have to mention the proper termination otherwise there is a probability for an infiniteloop.9. Doubly linked list take additional space to hold the address of the next node and address ofthe previous node.10. Linked list allows only sequential access to elements access time is greater.

Page 136: Data Structures Made Simple

EXERCISE

1. What is a linked list? 2. Define circular linked list. List out its advantage and disadvantages. 3. Define doubly linked list. 4. List out the advantages and disadvantages of Linked list. 5. Write a program to search a particular value in a singly linked list. 6. List out the different steps for the creation of linked list. 7. Write a C program to implement doubly linked list. 8. Explain circular linked list. 9. Write a C program to implement Circular linked list. 10. Explain circular doubly linked list. 11. Write a C program to implement Circular doubly linked list. 12. Write a C program to reverse the linked list.

Page 137: Data Structures Made Simple

Chapter Vll

TREES

7.1 Tree:

A tree is a finite set of nodes such that there is a special node called the ‘ROOT’ and remaining nodesare divided in to disjoined sets, where each of the set is a tree.

Figure 7.1 Tree

7.2 ROOT:

Root is a special node .It is the first node or top node in the tree. Every treehas only one root. In the above figure (7.1) ‘T’ is the root node.

7.3 Degree:

Degree of a node is the number of sub trees of the node, example, t1.t2, t3.Trees with ‘0’ degree isknown as leaf nodes or terminal nodes.

Page 138: Data Structures Made Simple

Root of the sub tree of a node is called children of the node. If X is a node, Y is a child of X then X iscalled the parent of Y.Nodes having the same parents are called as Siblings. The maximum degree ofnodes of a tree is called the degree of the tree. A path among two nodes X and Y of a tree is list ofnodes starting from X and ending in Y with no node repeating.

7.4 Pathlengh

The number edges on a path are called the length of the path. it is one less than the number of nodes inthe path.

7.5 Level

The level of the node is defined as follows:The level of the root is ‘1’, and then the level of the child is 1+ level of the parent.7.6 Forest

A set of trees which are disjoint (Having no common nodes) is called as forest.For example: If we take the tree in the above example and delete the root node, we get a forestconsisting of three disjoint trees.

Forest

AEF

Page 139: Data Structures Made Simple

BCDFGH

Figure 7.2 Forest

7.7 Labeled treesIf a label (name) is assigned to each node of a tree, then it is called a labeled tree.

A

BCD

Page 140: Data Structures Made Simple

FE

GH

Figure 7.3 Labeled tree

7.8 Binary tree A binary tree can be defined as tree in which every node has degree at most ‘two’. That is a tree is abinary tree if every node has ‘Zero’, ‘One’ or ’Two’ children. The two sub trees of a binary tree arecalled left sub tree and right sub tree.

Figure 7.4 Binary Tree

Page 141: Data Structures Made Simple

7.9 Application of trees

Trees have a variety of application. Some of them have listed below.

• Decision trees : when taking a decision we will have to consider several alternative and thedecision is based on various condition this can be formulated as a treeIf it rains or if it hot I will stay onside, else I will go out.

Figure 7.5 Decision Tree

• Game trees: many games like tick tack toe, chess, drought, etc can be modeled by trees. Herethe board positions are represented by nodes and edges represent moves. The root is the startposition and finding a good move requires searching the tree. • Representing sets: In a set element can be represented by nodes and disjoint sub sets can berepresented by sub trees. This representation makes operation like union very convenient.

• Oct trees and quad trees are used in computer graphics where a picture or a solid object isdivided in to different parts, and each part is further divided, forming a tree representation of thepicture or object. This representation saves much space and also is convenient for manipulatingpicture and objects. 7.10 Binary tree operations The common operations on a binary tree are:10. Inserting a node

Page 142: Data Structures Made Simple

First we create a new node with the item as value. Then we search the binary tree to find a nodeto which the given item can be inserted as the child node. We get a new binary tree with thegiven node inserted. 2. Deleting a nodeIn deletion there are three cases2. The node to be deleted is a leaf node.In this case in the parent of the node, the pointer to the node is made Null and the node is freed. 2. The node to be deleted has only one child.In this case in the parent of the node, the pointer to the node is replaced by a pointer to the onlychild and the node is freed. 3. The node has both a left child and a right child.In this case the inorder successor of the node is deleted after storing its value in a temporaryvariable. Then the value of the node is changed to the stored value. Consider a tree having sub trees on both sides; here we are going to delete the node 25, for thatwe need to find out the inorder successor of the node 25.We get the Inorder successor bytraversing the tree in inorder. Tree visited in sequence 20, 25,30,40,45,120,125,140,150. Fromsequence we found that 30 come after 25. After deletion tree looks like fig(7.5).

Figure (7.6) Figure (7.7) 3. Searching for a node.

Page 143: Data Structures Made Simple

It is examined whether a given node is in the tree or not.

Sample Program for implementing tree operations

Program 7.1 #include<stdio.h>#include<conio.h>#include<stdlib.h> struct BinaryTree{int n;struct BinaryTree *left;struct BinaryTree *right;}typedef BinaryTree;BinaryTree *root,*ptr,*prev,*bfor,*x,*y;int num; void main(){int ch;void createNewTree();void displayTree(BinaryTree *);void searchTree(BinaryTree *);void insertTree(BinaryTree *);void deleteTree(BinaryTree *); do{printf("\n1.CREATENEW\n2.PRINT\n3.SEARCH\n4.INSERT\n5.DELETE\n6.EXIT");printf("\nEnter your choice\t");scanf("%d",&ch);switch(ch){case 1 :{createNewTree();break;} case 2 :{displayTree(root);

Page 144: Data Structures Made Simple

break;}case 3 :{searchTree(root);break;}case 4 :{insertTree(root);break;} case 5 :{deleteTree(root);break;}}}while(ch<6);getch();} void createNewTree() // Creates a new binary tree{int n,i;BinaryTree *temp;root=NULL;printf("Enter the number of nodes\t");scanf("%d",&n);for(i=0;i<n;i++){printf("Enter the number ");scanf("%d",&num);if(root==NULL){temp=(BinaryTree *)malloc(sizeof(BinaryTree ));temp->n=num;temp->left=temp->right=NULL;root=temp;}else{ptr=prev=root;do

Page 145: Data Structures Made Simple

{if(num<ptr->n){prev=ptr;ptr=ptr->left;}else if(num > ptr->n){prev=ptr;ptr=ptr->right;}else{prev=NULL;break;}}while(ptr);if(prev){temp=(BinaryTree*)malloc(sizeof(BinaryTree));temp->n=num;temp->left=temp->right=NULL;if(temp->n<prev->n)prev->left=temp;if(temp->n > prev->n)prev->right=temp;}elseprintf("'%d' is already present..",num);}}} void displayTree(BinaryTree *ptr) // Displays the elements of the tree{if(!ptr){printf("Tree empty...");return;}void preorder(BinaryTree *ptr);printf("Root is '%d'",root->n);printf("\n Elements are .... ");preorder(root);}

Page 146: Data Structures Made Simple

void preorder(BinaryTree *ptr){if(!ptr)return;printf("%2d ",ptr->n);preorder(ptr->left);preorder(ptr->right);return;} void searchTree(BinaryTree *ptr) // Searches a particular element{if(!ptr){if(ptr == root){printf("Empty Tree");return;}}printf("Enter the number to search : ");scanf("%d",&num); while(ptr){if(ptr->n == num){printf("Search Successfull...");return;}elseif(ptr->n<num)ptr=ptr->right;elseptr=ptr->left;}printf("Search UnSuccessfull...");} void insertTree(BinaryTree *ptr) // Insert an element{

Page 147: Data Structures Made Simple

BinaryTree *temp;if(!ptr){printf("Tree is empty...First create & then insert... ");return;}ptr=prev=root;printf("Enter number to be inserted : ");scanf("%d",&num); do{if(num<ptr->n){prev=ptr;ptr=ptr->left;}else if(num > ptr->n){prev=ptr;ptr=ptr->right;}else{prev=NULL;break;}}while(ptr); if(prev){temp=(BinaryTree *)malloc(sizeof(BinaryTree ));temp->n=num;temp->left=temp->right=NULL;if(temp->n <prev->n)prev->left=temp;if(temp->n > prev->n)prev->right=temp;printf("'%d' is inserted...",num);}elseprintf("'%d' is already present...",num);return;}

Page 148: Data Structures Made Simple

void deleteTree(BinaryTree *ptr) // Deletes a particular element{if(!ptr){if(ptr == root){printf("Empty Tree");return;}}printf("Enter the number to be deleted : ");scanf("%d",&num);prev=ptr; while(ptr){if(ptr->n == num){if(ptr==root){x=ptr->right;root=x;while(x->left)x=x->left;x->left=ptr->left;free(ptr);printf("'%d' is deleted...",num);return;}else if(!(ptr->left) && !(ptr->right)){if(prev->left == ptr)prev->left=NULL;elseprev->right=NULL;free(ptr);printf("'%d' is deleted...",num);return;}else if(!(ptr->left)){if(prev->left == ptr){prev->left=ptr->right;

Page 149: Data Structures Made Simple

free(ptr);}else if(prev->right == ptr){prev->right=ptr->right;free(ptr);}printf("'%d' is deleted...",num);return;}else if(!(ptr->right)){if(prev->left == ptr){prev->left=ptr->left;free(ptr);}else if(prev->right == ptr){prev->right=ptr->left;free(ptr);}printf("'%d' is deleted...",num);return;}else{x=ptr->right;while(x->left)x=x->left;x->left=ptr->left;if(prev->left == ptr)prev->left=ptr->right;else if(prev->right == ptr)prev->right=ptr->right;free(ptr);printf("'%d' is deleted...",num);return;}}else if(ptr->n <num){prev=ptr;ptr=ptr->right;}

Page 150: Data Structures Made Simple

else{prev=ptr;ptr=ptr->left;}}printf("No Such Element Found..");} Output of the Program 1.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 1Enter the number of nodes 3Enter the number 50Enter the number 40Enter the number 60 1.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 2Root is '50'Elements are .... 50 40 601.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 4Enter number to be inserted : 70'70' is inserted...1.CREATENEW2.PRINT3.SEARCH

Page 151: Data Structures Made Simple

4.INSERT5.DELETE6.EXITEnter your choice 2Root is '50'Elements are .... 50 40 60 701.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 3Enter the number to search : 70Search Successfull...1.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 5Enter the number to be deleted : 60'60' is deleted...1.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 2Root is '50'Elements are .... 50 40 701.CREATENEW2.PRINT3.SEARCH4.INSERT5.DELETE6.EXITEnter your choice 6

7.11 Tree traversal methods

Page 152: Data Structures Made Simple

By traversing a tree, we mean visiting the nodes of the tree in a systematic fashion. Based on theorder in which we visit the nodes of a tree there are three tree traversal methods. The methods and the algorithm are given below: 3. Inorder traversalTraverse the left subtree in Inorder, visit the root and traverse the right sub tree in Inorder.2. Pre order traversalVisit the root node, traverse the left sub tree in pre order, and traverse the right sub tree in preorder.3. Post order traversalTraverse the left sub tree in post order, traverse the right sub tree in post order, and visit theroot.We can explain the tree traversal with the following example.

Figure 7.8 Inorder traversal 20, 25, 30, 40, 45, 120, 125, 140,150Pre-order traversal 120, 45, 25, 20, 40, 30, 140, 125, 150Post-order traversal 20, 30, 40, 25, 45, 125, 150, 140, 120 Sample program for tree traversal

Program 7.1#include<stdio.h>

struct treenode1{struct treenode1 *left;char data;struct treenode1 *right;

Page 153: Data Structures Made Simple

};typedef struct treenode1 tree;tree *root=NULL;void inserttree();void inorder(tree*);void postorder(tree*);void preorder(tree*);int number,no;void main(){int i,option;printf("\n\tTree Operation-Menu\n");printf("\n1.InsertNode\n2.Inorder\n3.Preorder\n4.Ppostorder\n5.Exit\n");do{printf("\nEnter your operation\t");scanf("%d",&option);switch(option){case 1:inserttree();break;case 2:printf("\nIn order traversal\n");inorder(root);break;case 3:printf("\nPre order traversal\n");preorder(root);break;case 4:printf("\nPost order traversal\n");postorder(root);break;}}while(option<5);getch();}void inserttree() // Insert nodes to tree{tree *t,*p,*q;printf("Enter a number\t");scanf("%d",&number);q=(tree*)malloc(sizeof(tree));q->data=number;

Page 154: Data Structures Made Simple

q->left=NULL;q->right=NULL;if(root==NULL){root=q;return;}p=root;t=NULL;while(p!=NULL){t=p;if(p->data>number)p=p->left;elsep=p->right;}if(t->data>number)t->left=q;elset->right=q;}void inorder(tree *p){if(p!=NULL){inorder(p->left);printf("%d ",p->data);inorder(p->right);}}void preorder(tree *p){if(p!=NULL){printf("%d ",p->data);preorder(p->left);preorder(p->right);}}void postorder(tree *p){if(p!=NULL){postorder(p->left);

Page 155: Data Structures Made Simple

postorder(p->right);printf("%d ",p->data);}}

Output of the Program

Tree Operation-Menu1.InsertNode2.Inorder3.Preorder4.Ppostorder5.ExitEnter your operation 1Enter a number 50Enter your operation 1Enter a number 90Enter your operation 1Enter a number 80Enter your operation 1Enter a number 40Enter your operation 1Enter a number 30Enter your operation 2In order traversal30 40 50 80 90Enter your operation 3Pre order traversal50 40 30 90 80Enter your operation 4Post order traversal30 40 80 90 50Enter your operation 5

7.12 Binary Search tree

Page 156: Data Structures Made Simple

A binary search tree is a binary tree with the following properties.• The value of every node is unique.• The value of each node in the left sub tree is less than the value of any node in the right subtree.• The value of any node in the left sub tree is less than the value of the root.• The value of any node in the right sub tree is greater than the value of the root.• Sub trees also satisfy the above properties. 7.13 Threaded binary treeA threaded binary tree is a binary tree in which every node without a right child has a pointer toits successor in an Inorder traversal. These pointers are called threads.

Page 157: Data Structures Made Simple

Figure 7.9 Threaded binary tree 7.14 Use of threaded binary trees Threaded binary tree can be used in tree traversal. If we use a threaded binary tree we can avoidrecursion and the use of stacks. This saves a lot of memory and is much faster than recursivemethods.

Page 158: Data Structures Made Simple

Exercises

3. What is tree?4. Define sub tree.5. Define root node and leaf node.6. Define degree and level of a tree.7. Explain the terms forest and labeled tree.8. Explain the Application of trees.9. What is a binary tree? Discuss the binary tree operation.10. Discuss the different tree traversal methods.11. What is binary search tree?12. What is threaded binary tree?11. Write a C program to implement the binary tree operations.12. Write a c program to implement tree traversal.13. Discuss the use of threaded binary tree.

Page 159: Data Structures Made Simple
Page 160: Data Structures Made Simple

Chapter VlllGRAPH

8.1 Graph

Graph is also a nonlinear data structure which has application in many areas like networking,

geographical information systems, traffic planning’s, project management and chemistry.8.2 Definition

A graph G consists of a set of V of vertices and a set E of edges between the vertices. It can be

represented as G= (V, E). Where V is a finate set of vertices and E is a set of pairs of vertices callededges.

Figure 8.1 Graph

A graph can be either directed or undirected. In an undirected graph every edge is represented byunordered pair of vertices, whereas in a directed graph the edges are represented by ordered pairs ofvertices. That is ,if u and v are vertices then in a directed graph an edge from u to v is represented as(u,v) and an edge from v to u is represented by (v,u).Also these are different edges. But in undirectedgraph (u,v) and (v,u) represent same edge between u and v.We use directed arrows to draw an edgein a directed graph and undirected line segments to draw edges in an undirected graph .see figuresbelow

Page 161: Data Structures Made Simple

Figure 8.3 Figure 8.4

If( x, y) is an edge in a directed graph we say that xis adjacent to y. and y is adjacent from x.In

the case of a undirected graph if (x,y ) is an edge, we say that x and y are adjacent. In the aboveexample in figure (8.3), vertex a is adjacent to vertex c and vertex c is adjacent from a. In figure (8.4)vertices a and c are adjacent to each other.

A subgraph of a graph G=(V,E) is a graph G’ =(V’,E’) such that the vertex set V’ of G’ is asubset of the vertex set V of G,and the set of edges E’of G’ is a subset of the set of edges E of G.

A path from a vertex x to a vertex y in a graph G is a sequence of vertices.x =v0 ,v1,…,vr=y such that all vertices except possibly the first and last are distinct and (v0,v1),(v1,v2),…,(vr-1,vr) are edges in G.The number of edges in a path is called Length of a path. A cycle isa path with first and last matrix is same.

An undirected graph is said to be connected if there is a path between every two distinct vertices.Other wise it called as disconnected.Representation of a GraphA graph can be represented in many ways, but the most used methods are givenbelow:

1. Adjacency matrix representation2. Adjacency list representation 8.3 Adjacency matrix representation Here a graph with n vertices {v1,v2,…,vn} is represented by an nxn matrix A. This matrix iscalled the adjacency matrix of the graph. In this matrix, the i,j th entry A[i,j] is 1 if there is anedge from vertex i to vertex j. Otherwise it is ‘0’. Example:

Page 162: Data Structures Made Simple

Figure 8.5 Directed graph Figure 8.6 Adjacency Matrix

Figure 8.7 Figure 8.8

8.4 Adjacency list representation

Page 163: Data Structures Made Simple

In Adjacency list representation a linked list consisting of vertices adjacent to given vertex is attachedto the vertex.

Figure 8.9 Figure 8.10

8.5 DFS and BFS

Given an undirected graph G and a vertex x, we may want to visit all vertices in G which arereachable from x in a systematic fashion. There are many methods to do this. Two of the most popularmethods are listed below:

13. Depth First Search (DFS).14. Breadth First Search (BFS).

8.6 Depth First Search (DFS).

In DFS we are going to visit the vertices in depth wise fashion. Starting from a vertex we are going tovisit one of its neighbors, and then one of its neighbors and so on until the current vertex has nounvisited neighbors. Then we backtrack and continue visiting the next neighbor of the earlier vertex.Figure (8.13) shows the DFS spanning tree for the tree given in figure (8.11).

8.7 Breadth First Search (BFS)

In breadth first search we visit the vertices in a breadth wise fashion. Here first of all we start from avertex, then visit all its neighbors, and then visit the neighbors of the neighbors and so on. Queue data

Page 164: Data Structures Made Simple

structure is used here. Figure (8.12) shows the BFS spanning tree for the tree given in figure (8.11).

Figure 8.11 Figure 8.12

Figure 8.13

In the figures above an undirected graph is visited starting from vertex 1. The DFS and BFS generatetrees called the DFS tree and BFS tree respectively. These trees contain all the vertices of the graphG and are spanning trees.

BFS algorithmInput : A graph G and a source vertex s of GOutput: A BFS Tree of the graph

14. Create a queue Q15. Add s to Q16. mark s17. make s as the root of the tree T

Page 165: Data Structures Made Simple

5. while Q is not empty:6. Remove a vertex v from Q7. for each edge (v ,w) of G8. if w is not marked:9. mark w,10. Make v the parent of w in T11. add w to Q12. end if13. end while14. Return T15. STOP

Time complexity of BFSSince in the worst case BFS will have to consider all edges, the time complexity is O(m+n) on agraph with n vertices and m edges.Space complexity of BFS

Applications of BFSBreadth first search has many applications. Some of them are given below.1 .Identifying connected components of a graph. BFS can be used to find all connected components in a graph. By starting from an arbitrary vertex BFS ends when all the vertices whichare connected to that vertex is explored. Then start ing from a remaining vertex we get the next connected component.In this way wecan find all the connected components. 2.Checking weather a graph is bipartite or not A bipartite graph has the property that it has no cycles with an odd number of vertices. A bipartitegraph can be recognosed by BFS.

3.Finding the shortest path from one vertex to all other vertices.A BFS starting from a single vertex gives a tree in which the path from the root to any other vertex isa shortest path.

DFS algorithmBFS algorithmInput : A graph G and a source vertex s of GOutput: A DFS Tree of the graph

Page 166: Data Structures Made Simple

15. Create a Stack R16. Push s to R17. mark s18. make s as the root of the tree T

5. while R is not empty:6. pop a vertex v from R7. for each edge (v ,w) of G8. if w is not marked:9. mark w,10. Make v the parent of w in T11. push w to R12. end if13. end while14. Return T15. STOP

Time complexitySince in the worst case DFS will have to consider all edges of the graph and all vertices, the timecomplexity is O(m+n) on a graph with n vertices and m edges.

ApplicationsDFS have a wide variety of applications.Some of them are given below.

15. .Finding the connected components of a graph.16. In game playing17. Solving mazes18. Checking weather a given graph is planar (Weather it can be drawn on the pane withoutedges crossing)

5.Topological sorting.Notice That The only difference between DFS and BFS is that we use a Stack in DFS instead of aqueue in BFS.

8.8 Shortest path and Dijkstra Algorithm

A shortest path from a vertex x to y in a graph G is a path from x to y having minimum number ofedges .The length of any shortest path from x to y is the distance from x to y, and is denoted byd(x,y)..In an undirected graph d(x, y) and d(y, x) are same.

Page 167: Data Structures Made Simple

8.9 Weighed graph

A directed graph in which weights are assigned on edges is called a weighted graph.

Figure 8.14

A weighed graph may be used to represent many real life problems. For example a weighed graphmay represent a road net work. Here vertices may represent cities; edges may represent roadsbetween the cities. Weights indicating the cost of moving from one city to another city.A shortest path from a vertex x to a vertex y is a path from x to y B such that the sum of the weights ofthe edges in the path is minimum.

8.10 Dijkstra Algorithm

Dijkstra algorithm is used to find the shortest path and the costs of the paths froma given vertex x to all other vertices in a weighed graph G.Here we assume that all the costs are non-negative. Dijkstra’s Algorithm works by keeping a set ofvertices whose distance from x is already determined. The algorithm proceeds by selecting a vertex vnot in S, whose distance from all vertices of S is minimum. The time complexity of the algorithm is O(n2), where n is the number of vertices. The following program implements the algorithm

Program 8.1 #include <stdio.h>

Page 168: Data Structures Made Simple

int distanceMatrix[20][20]; // To store the distance matrix int shortestPath[20]; // To store the shortest paths int findMax(int a, int b) // Find maximum of two numbers { if(a>b) return a; else return b; } void printPath(int sv,int n)// displays the shortest paths { int i; printf("From To ShortestPath\n\n"); for (i = 1; i <= n; ++i) { printf("%d %d %ld\n",sv,i,shortestPath[i]); } printf("\n"); }

void findPath(int sv,int n) //Find the shortest paths using Dijkstra's algorithm { int i,j,minimum; int checked[20]; for (i = 1; i <= n; ++i) { shortestPath[i] = 9999; checked[i] = 0; // Setting all vertices as unvisited }

shortestPath[sv] = 0;

for (j = 1; j <= n; ++j) {

Page 169: Data Structures Made Simple

minimum = -1; for (i = 1; i <= n; ++i) { if (!checked[i] && ((minimum == -1) || (shortestPath[i] < shortestPath[minimum]))) minimum = i; } checked[minimum] = 1; for (i = 1; i <= n; ++i) { if (distanceMatrix[minimum][i]) { if (shortestPath[minimum] + distanceMatrix[minimum][i] < shortestPath[i]) { shortestPath[i] = shortestPath[minimum] + distanceMatrix[minimum][i]; } } } } }

int main() { int i,j,from,to,distance; int n; int n_of_edges; int sourceVertex; printf("Enter the number of edges\t"); scanf("%d", &n_of_edges); for (i = 0; i < n_of_edges; ++i) for (j = 0; j < n_of_edges; ++j) distanceMatrix[i][j] = 0; n = -1; printf("Enter the edges in the order from--to--distance\n"); for (i = 0; i < n_of_edges; ++i) { scanf("%d%d%d", &from, &to, &distance); distanceMatrix[from][to] = distance;

Page 170: Data Structures Made Simple

n = findMax(from, findMax(to, n)); } printf("Enter the Source Vertex\t"); scanf("%d",&sourceVertex); findPath(sourceVertex,n); printPath(sourceVertex,n); getch(); return 0; }

Output of the Program

Enter the number of edges 10 Enter the edges in the order from--to--distance 1 2 10 2 3 1 1 4 5 2 4 2 4 2 3 4 5 2 4 3 9 3 5 4 5 3 6 5 1 7 Enter the Source Vertex 1 From To ShortestPath

1 1 0 1 2 8 1 3 9 1 4 5 1 5 7

Page 171: Data Structures Made Simple

Warshalls algorithm (Floyd warshall Algorithm) For finding all pairs of shortest paths. In a weighted directed graph, Floyd warshall algorithm can be used to find all pairs of shortest paths(distances between any pair of points) The algorithm is given below Algorithm Input: The adjacency matrix of a directed weighted graph. Output: a matrix d representing the shortest distances

18. for i=0 to n-1 19. for j=0 to i-1 20. If(w[i][j]==0) 21. d[i][j]= infinity 22. else 23. d[i][j]=W[i][j] 24. for i=0 to n-1 25. d[i][i]=0

9. for k = 0 to n-1 10. for i = 0 to n-1 11. for j = 0 to n-1 12. d[i][j] = min ( d[i][j], d[i][k]+d[k][j] ) 13. STOP

The complexity of the algorithm is O(n3),Where n is the number of vertices of the graph.

Exercises

13. Define graph.

Page 172: Data Structures Made Simple

14. Explain Direct and undirected graph.15. How can we represent graphs?16. Define sub graph.17. Define path.18. Explain Adjacency matrix with an example.19. Explain Adjacency list with an example.20. Explain DFS and BFS.21. What is shortest path?22. What is weighted graph?23. Explain and Implement Dijkstra algorithm.

Exercises

Page 173: Data Structures Made Simple

12. Define graph.13. Explain Direct and undirected graph.14. How can we represent graphs?15. Define sub graph.16. Define path.17. Explain Adjacency matrix with an example.18. Explain Adjacency list with an example.19. Explain DFS and BFS.20. What is shortest path?21. What is weighted graph?22. Explain and Implement Dijkstra algorithm.