P. 1
dfs

dfs

|Views: 75|Likes:
Published by Premendra Yadaw

More info:

Published by: Premendra Yadaw on Feb 18, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

12/27/2012

pdf

text

original

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt.

 Ravishankar Shukla University,Raipur

 

1
1.1 INTRODUCTION

PREREQUISITE

In this chapter- concept of data, data structure, structural programming, top down design, abstract data type, array, structure, character strings, pointers, dynamic memory allocation and pointer to structure is covered. In array one, two and multi dimensional arrays with their operations are discussed. The implementation of structure is covered with the help of example. The character strings with their storage structure and operations are covered in this chapter. The pointer with their dynamic allocation is also discussed. The implementation of structure with the help of pointer is also covered.

1.2 CONCEPT OF DATA REPRESENTATION
Data is simply values or sets of values. A data field refers to a single unit of values. Data items or fields that are divided into sub-items are called group items. For example, an employee name may be divided into three parts- first name, middle name and last name. Those that are not divided into sub-items are called elementary or single items like- social security number. Collection of data is frequently organised into hierarchy of fields, records and files. A field is a single elementary unit of information representing an attribute of an entity, a record is the collection of field values of a given entity and a file is the collection of records of the entities in a given set. For example, an employee is an entity; his attributes(fields) and values are : Attributes : Name Age Sex Social_Security_Number Values : S. Jain 27 M 100-00-222 Entities with the similar attributes like- set of the entire employee form an entity set.

1.3 DATA STRUCTURES
Data may be organised in many different ways, the logical and mathematical model of a particular organisation of data is called a data structure. The choice of a data model depends on the consideration, that it must be rich enough in structure to mirror the actual relationships of the data in the real world and the structure should be simple enough so that, one can efficiently process the data, when necessary.
(1)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

2 Data Structures

Data Structure = Organised Data + Allowed Operations The data structure is a collection of data elements that can be characterised by its organisation and the operations that are defined on it, i.e., “The organised collection of data is called data structure”. The data structures are classified into the following categories : (i) linear data structures, (ii) non linear data structures. (i) Linear Data Structures : In this type of data structures, processing of data items is possible in linear manner, i.e., data can be processed one by one sequentially. It contains the following type of data structures : (a) array, (b) linked list, (c) stack and queue. (ii) Non Linear Data Structures : In this type of data structures, insertion and deletion is not possible in a linear manner. It contains the following type of data structures : (a) tree, (b) graph. 1.3.1 Operations on Data Structures : The data appearing in data structures are processed by means of certain operations. In fact, the particular data structures that one chooses for a given situation depends largely on the frequency with which specific operations are performed. The following are the operations of data structures, which play major role in the processing of data : (i) Traversing : Accessing each record exactly once so that certain items in the record may be processed. This accessing is also known as visiting. (ii) Searching : Finding the location of the record with a given key item or finding the location of all records which satisfy one or more conditions. (iii) Inserting : Adding a new record in the data. (iv) Deleting : Removing a record from the data. (v) Sorting : Arranging the records in some logical order (numerical or alphabetical order). (vi) Merging : Combining the records in two different sorted files into a single sorted file. For example, an organisation contains a membership file in which each record contains the following data for a given member : Name Address Tele_number Age Sex (i) Suppose we want to find the names of all members, then we would traverse the file to obtain the data.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 3

(ii) Suppose we want to obtain address for a given name, then we would search the file for the record containing the name. (iii) Suppose a new person joins the organisation, then we would insert the record into the file. (iv) Suppose a member dies, then we would delete the relative record from the file.

1.4 STRUCTURAL PROGRAMMING
The structural programming provide a well-defined, clear and simple approach to program design. This method is easier to understand, evaluate and modify. It has single entry and a single exit. So, we know that the execution starts with the first statement and terminates with the last statement in the sequence. The clarity and modularity in structural programming help in finding an error and redesigning the required section of code. The structural programming requires the following three control constructs to implement the program design : (i) Sequence Construct : It is simply a sequence of two or more statements, which can be executed in a sequence. Statement1

Statement2

Statement3
Fig. 1.1

(ii) Conditional Construct : In this construct, the execution of statements depends on the condition. We can alter the order of statements execution by using selection and iteration.

True

Condition

False

Statement1
Fig. 1.2

Statement2

(iii) Looping Construct : In this construct, the sequence of statements is executed repeatedly as long as the condition is true. It is known as looping or iteration.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

4 Data Structures

True

Condition

False

Statement

Fig. 1.3

1.5 TOP DOWN DESIGN
The top down design is a technique for stepwise refinement of algorithm design. In this technique, the whole concentration is on the major problem. The top down design approach represents a successive refinement of functions and the process of refinement is continued until the lowest level module can be designed without further analysis. In this design approach, we take the general statements that we have about the solution, one at a time and break them down into a set of more precisely defined sub-problems. These sub-problems should more accurately describe how the final goal is to be reached. It is necessary that the way, in which the sub-problems need to interact with each other, be precisely defined. Only in this way it is possible to preserve the overall structure of the solution to the problem. The process of repeatedly breaking down a problem into sub-problems and then each sub-problem into still smaller sub-problems must continue until we eventually end up with sub-problems, which can be implemented as program statements. The top down design structure is viewed as tree structure shown in figure 1.4. The module is divided into sub-modules and the doted boxes represent the non-leaf module. X

Y

Z

W

V
Fig. 1.4

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 5

1.6 ABSTRACT DATA TYPE
All programming languages use a set of predefined data types, known as base data types, which describe a set of objects with similar characteristics. Base data types are subject to a predefined set of operations. For example, the integer data type allows operations such as addition, subtraction, multiplication and division. Like base data types, abstract data type describes a set of similar objects. However, abstract data type operations are user defined. In defining an abstract data type as a mathematical concept, we are not concerned with its implementation issues like- time and space requirements. To understand ADT clearly, let us see, which is meant by abstraction. An abstraction is the structuring of a nebulous problem into welldefined entities by defining their data and operations. Consequently, these entities combine data operations. They are not decoupled from each other. The data structure can only be accessed with defined operations. This set of operations is called interface and is exported by the entity. An entity with the properties just described is called an abstract data type(ADT). Figure 1.5 shows an ADT, which consists of abstract data structure and operations. Only the operations are viewable from the outside and define the interface. Abstract Data Type Abstract Data Structure

Operations

Interface

Fig. 1.5 An Abstract Data Type

1.7 ARRAY
“An array is a structured data type made up of a finite, fixed size, collection of homogenous ordered elements”. Homogenous means, all the elements are of the same data type, ordered means all elements are arranged sequentially, finite means there is a last element and fixed size means that the size of the array must be known at compile time. The accessing mechanism of array is direct, which means we can access any element directly without first accessing the preceding elements; accessing is done by the use of an index that allows us to specify the desired element by giving its position in the collection.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

6 Data Structures

1.7.1 One Dimensional Array : The array whose items are specified by one subscript are known as one-dimensional array. 1.7.1.1 Storage of One Dimensional Array in Memory : The data represented in an array is actually stored in the memory cells in straightforward manner because computer memory is linear. Storage for element X[I+1] will be adjacent to storage for element X[I] for I=1,2, ….. N. To find the actual address of an element, we need to subtract lower bound from the position of the desired entry and then add the result to the address of the first cell in the sequence and multiply it by the size of each element of array. B+(I-L)*S Where B is the address of the first cell of array called base address and S is the size of each element of array. I is the position of the desired entry and L is the lower bound of the subscript. For example, let us take an array X of 20 elements and we desire to find the address of element X[6]. If the first cell in the sequence is at address 100 and suppose that the size of each element stored is one byte, what is the address of X[6]? B = 100 I =6 L=1 S=1 Address of X[6] = 100*(6 –1)*1 = 100+5 = 105 To find the total number of cells required of an array, we need to subtract lower bound from upper bound, add one to it and multiply it with the size of each element of array. Number of Cell = [(upper bound – lower bound)+1]*size = [(UB – LB)+1]*S For example, let us take an array X[2..20]. If the base address is 20 and size of each element is 1 unit then to find out the address of X[4] and also the total number of cells required for storage, we shall proceed in the following manner : B = 20 L =2 I=6 S=4 Address of X[6] = 20+(6-2)*4 = 20+4*4 = 20+16 = 36 Number of Cell = [(20-2)+1]*4

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 7

= [18+1]*4 = 19*4 = 76 1.7.1.2 Declaration of One Dimensional Array : There are three things that need to be specified to declare a one dimensional array in most of the programming languages : (i) the type of data to be stored in data elements, (ii) the array name, (iii) the subscript or index range. In C language, the array can be declared as follows : storage_class type_specifier Array_name[index] For example, int list[20]; char color[40]; In first declaration list is the array’s name; the elements of list can hold integer data and the number of elements is 20 i.e., subscripts range from 1 to 20. Similarly, In second declaration color is the array’s name; the elements of color can hold character data and the number of elements is 40 i.e., subscripts range from 1 to 40. An array declaration tells the computer two major pieces of information : (i) The range of subscript allows the computer to determine how many memory locations must be allocated. (ii) The array type tells the computer how much space is required to hold each value. 1.7.1.3 Initialisation of One Dimensional Array : An array can be initialised just like other variable. By default the array elements are set to 0. The following are the ways of initialising an array: storage_class type_specifier Array_name[index] = { __,__,__ } We can use a comma as a separator between two values. In another way, we can also initialise the array in which we can omit the size of the array at the time of initialisation. storage_class type_specifier Array_name[] = { __,__,__ } For example, int price[4] = {25,30,40,50}; After the initialisation, the array price will take the initial values as follows : price[0] = 25 price[1] = 30 price[2] = 40 price[3] = 50 The memory representation of the array price is shown in table 1.1.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

8 Data Structures

Table 1.1 Array price in Memory
INDEX INFO

0 1 2

25 30 40

3 50 double salary[] = {1000,2000,3000,4000,5000}; In this case, the computer is able to calculate the size of the array. The number of initialisers can be equal to or less than the size of the array. It can not be more than the size of the array. The following initialisation generates an error message at the time of compilation. int list [4] = {12,23,34,45,56}; Let us take an example in which we show the initialisation of array of character. char city[8] = “Gwalior”; In this case, the array city is initialised by the string “Gwalior”. The last element is the terminator ‘\0’ character. We can also initialise the character array with less than the size of the array defined. char book[20] = “Data Structure”; In this case, the remaining elements in the array are initialised with ‘\0’ characters. If the string is equal to or greater than the array size, the compiler will give the error message. char book[12] = “Data Structure”; It is possible to omit the size of the array at the time of initialisation. For example, an array can be initialised as follows : char name[] = “Prof. Sanjay Jain”; In this case, the computer is able to calculate the size of the array. 1.7.1.4 Various Operations of One Dimensional Array : Let us suppose that LIST is a one-dimensional linear array of integers. The following are the operations, which are performed on the one dimensional array : (i) Traversal Operation : Traversing is the process by which we can visit or access and process each element of array exactly once. For example, suppose we have an array LIST of integers in the computer memory, as shown in table 1.2. If we want to visit each element of array LIST then this visiting process is called traversing.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 9

Table 1.2 LIST of Integers
INDEX INFO

0 1 2 3 4 5 6 7 8

4 8 12 16 20 24 28 32 36

9 40 (A) Algorithm : Following are the steps for traversal operation : (a) [Initialise the counter] Set (counter) i = 0 (b) [Traverse each element of the array] Repeat Step (c) and (d) while i <= n (c) [Visit element and performs the operation] Apply operation to list[i] (d) [Increment counter] Set i := i +1 (e) End. (B) Equivalent C Function void traversal(int list[], int n) { int i; i=0; while(i<n) { printf("Element at position %d is:",i); printf("%d\n",list[i]); i++; } } (C) Implementation of Traversal Function : The following program array_traversal.c shows the array implementation of the traversal function for integers stored in the computer memory :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

10 Data Structures

/*array_traversal.c*/ #include<stdio.h> #include<stdlib.h> void traversal(int[],int); void main() { int i=0,list[100],n; printf("This program performs the one dimensional array traversal operation on numbers!\n"); printf("How many numbers in the array:"); scanf("%d",&n); printf("!!Please enter the number!!\n"); while(i<n) { printf("Input value for the %d:",i); scanf("%d",&list[i]); i++; } traversal(list,n); } void traversal(int list[], int n) { int i=0; printf("!!Entered element in the array after traversing the array are!!\n"); while(i<n) { printf("Element at position %d is:",i); printf("%d\n",list[i]); i++; } printf("\n"); } (D) Output of the Program This program performs the one dimensional array traversal operation on numbers! How many numbers in the array:8 !!Please enter the number!! Input value for the 0: 12 Input value for the 1: 23 Input value for the 2: 34

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 11

Input value for the 3: 45 Input value for the 4: 56 Input value for the 5: 67 Input value for the 6: 78 Input value for the 7: 89 !!Entered element in the array after traversing the array are!! Element at position 0 is: 12 Element at position 1 is: 23 Element at position 2 is: 34 Element at position 3 is: 45 Element at position 4 is: 56 Element at position 5 is: 67 Element at position 6 is: 78 Element at position 7 is: 89 (ii) Insertion Operation : Insertion is the operation by which we can add an element in the array at the desired position. For example, suppose we have an array of multiple of 4, named as TABLE, as shown in table 1.3. But by mistake we forget one of the table entry 24. Now, we want to insert 24 in the proper place so that we get the desired table of 4. By inspecting the array, we find that 24 is missing at position 6. Before inserting 24 in the array, we have to move each element of the array from position 6 to 9, one position down. For this the following steps are performed : Table 1.3(a) Table of Multiple of 4 Table 1.3(b) After Insertion 24
INDEX INFO INDEX INFO

0 1 2 3 4 5 6 7 8

4 8 12 16 20 28 32 36 40

0 1 2 3 4 5 6 7 8

4 8 12 16 20 24 28 32 36

9 9 40 I=9 [Represents number of elements in the array] TABLE[9]=TABLE[8]=40 I = I –1 = 9-1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

12 Data Structures

TABLE[8]=TABLE[7]=36 I = I –1 = 8-1 TABLE[7]=TABLE[6]=32 I = I –1 = 7-1 TABLE[6]=TABLE[5]=28 I = I –1 = 6-1 TABLE[5]=24[Newly inserted element] The result after insertion of 24 is shown in table 1.3(b). (A) Algorithm : Following are the steps for insertion operation : (a) [Initialise the counter with the size of the array] Set (counter) i := n (b) [Traverse each element of the array until we find the desired position] Repeat step (c) and (d) while i >= position(desired position) (c) [Move element downward] Set list[i+1] := list[i] (d) [Decrease counter] Set i := i –1 (e) [Insert element at the desired position] Set list[position] := item (f) [Reset the array size] Set n = n+1 (g) [Return the new array size] return(n) (h) End. (B) Equivalent C Function int insertion(int list[], int n, int position, int item) { int i; i=n; while(i>=position) { list[i+1] = list[i]; i--; } list[position] = item; n= n+1; return n; } (C) Implementation of Insertion Function : The following program array_insertion.c shows the array implementation of the insertion function for integers stored in the computer memory :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 13

/*array_insertion.c*/ #include<stdio.h> #include<stdlib.h> int insertion(int[],int,int,int); void display(int[],int); void main() { int i=0,list[100],n,position,item; printf("This program performs the one dimensional array insertion operation on numbers!\n"); printf("How many numbers are there in the array:"); scanf("%d",&n); printf("!!Please enter the number!!\n"); while(i<n) { printf("Input value for the %d:",i); scanf("%d",&list[i]); i++; } display(list,n); printf("Enter the position where we want to add a new number:"); scanf("%d",&position); printf("Please enter the number for the position:"); scanf("%d",&item); n = insertion(list,n,position,item); display(list,n); } void display(int list[], int n) { int i=0; printf("!!Entered elements in the array are!!\n"); while(i<n) { printf("Element at position %d is:",i); printf("%d\n",list[i]); i++; } printf("\n"); } int insertion(int list[], int n, int position, int item) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

14 Data Structures

int i; i=n; while(i>=position) { list[i+1] = list[i]; i--; } list[position] = item; n= n+1; return n; } (D) Output of the Program This program performs the one dimensional array insertion operation on numbers! How many numbers are there in the array: 5 !!Please enter the number!! Input value for the 0: 12 Input value for the 1: 23 Input value for the 2: 34 Input value for the 3: 56 Input value for the 4: 67 !!Entered elements in the array are!! Element at position 0 is: 12 Element at position 1 is: 23 Element at position 2 is: 34 Element at position 3 is: 56 Element at position 4 is: 67 Enter the position where we want to add a new number: 3 Please enter the number for the position: 45 !!Entered elements in the array are!! Element at position 0 is: 12 Element at position 1 is: 23 Element at position 2 is: 34 Element at position 3 is: 45 Element at position 4 is: 56 Element at position 5 is: 67 (iii) Deletion Operation : Deleting an element from the end of an array is simple but deleting an element from the desired position is difficult and requires moving all the elements up-word to fill up the gap into the array.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 15

(A) Algorithm : Following are the steps for deletion operation : (a) [Initialise the counter with the size of the array and assign the desired position data value to item] Set (counter) i := n & item := list[position] (b) [Update the list] Repeat step (c) and (d) while (position <= n) (c) [Move element upward] Set list[position] := list[position+1] (d) [Increase counter] Set position := position +1 (e) [Reset the array size] Set n = n-1 (f) [Return the new array size] return(n) (g) End. (B) Equivalent C Function int deletion(int list[], int n, int position) { int i,item; i=n; item = list[position]; printf("Deleted item from the position %d is : %d\n", position,item); while(position<=n) { list[position] = list[position+1]; position++; } n= n-1; return n; } Table 1.4(a) List of Number Table 1.4(b) After Deleting 45
INDEX INFO INDEX INFO

0 1 2 3 4 5 6 7

12 23 34 45 56 67 78 89

0 1 2 3 4 5 6 7

12 23 34 56 67 78 89

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

16 Data Structures

For example, suppose we have a list of 7 number LIST, as shown in table 1.4. If we want to delete the number 45, it is required to update list of numbers. After deleting 45 at the position 4, it is necessary to move each element of the array from position 5 to 8 one position up. For this the following steps are performed : Position of the number 45 in the list is 4. LIST[3]=LIST[4]=56 LIST[4]=LIST[5]=67 LIST[5]=LIST[6]=78 LIST[6]=LIST[7]=89 LIST[7]=NULL The resulting list after deletion is shown in table 1.4(b). (C) Implementation of Deletion Function : The following program array_deletion.c shows the array implementation of the deletion function for integers stored in the computer memory : /*array_deletion.c*/ #include<stdio.h> #include<stdlib.h> int deletion(int[],int,int); void display(int[],int); void main() { int i=0,list[100],n,position; printf("This program performs the one dimensional array deletion operation on numbers!\n"); printf("How many numbers are there in the array:"); scanf("%d",&n); printf("!!Please enter the number!!\n"); while(i<n) { printf("Input value for the %d:",i); scanf("%d",&list[i]); i++; } display(list,n); printf("Enter the position from where we want to delete a number:"); scanf("%d",&position); n = deletion(list,n,position); display(list,n); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 17

void display(int list[], int n) { int i=0; printf("!!Entered elements in the array are!!\n"); while(i<n) { printf("Element at position %d is:",i); printf("%d\n",list[i]); i++; } printf("\n"); } int deletion(int list[], int n, int position) { int i,item; i=n; item = list[position]; printf("Deleted item from the position %d is :%d\n",position,item); while(position<=n) { list[position] = list[position+1]; position++; } n= n-1; return n; } (D) Output of the Program This program performs the one dimensional array deletion operation on numbers! How many numbers are there in the array: 5 !!Please enter the number!! Input value for the 0: 12 Input value for the 1: 23 Input value for the 2: 34 Input value for the 3: 45 Input value for the 4: 56 !!Entered elements in the array are!! Element at position 0 is: 12 Element at position 1 is: 23 Element at position 2 is: 34 Element at position 3 is: 45

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

18 Data Structures

Element at position 4 is: 56 Enter the position from where we want to delete a number: 3 Deleted item from the position 3 is : 45 !!Entered elements in the array are!! Element at position 0 is: 12 Element at position 1 is: 23 Element at position 2 is: 34 Element at position 3 is: 56 1.7.2 Multi Dimensional Array : If There are two or more subscripts for referencing array elements then it is called multi dimensional array. A two dimensional array is a structured data made up of a finite collection of homogenous elements. Each element is ordered in two dimensions. The accessing is done with the help of a pair of subscripts, which allows us to specify which element in the collection we want to access. The first subscript represents the elements position(rows) and other represents the elements(columns). 1.7.2.1 Storage of Two Dimensional Array in Memory : The two dimensional array will be represented in memory by a block of mxn sequential memory locations. To find the actual address of an element in two dimensional array we use the following formula : For column : LOC(LIST[j,k]) = B + W*[m*(k-1) +(j-1)] For row : LOC(LIST[j,k]) = B + W*[n*(j-1) +(k-1)] Where B is the address of the first cell of array and is called base address and W is the size of each element of array. m represents the first index of the array and n represents the second index of the array. j and k represent the desired element first and second subscript, respectively. For example, let us take an array LIST[20,5]. Suppose B(LIST) = 100 and there are W=5 words per memory cell. Calculate the address of LIST[5,2]. For row : LOC(LIST[j,k]) = B + W*[n*(j-1) +(k-1)] j=5 k=2 W=5 B = 100 m = 20 n=5 LOC(LIST[5,2]) = 100 + 5*[5*(5-1)+(2-1)]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 19

= 100 + 5*[5 *4+1] = 100 + 5*[20+1] = 100 + 5*21 = 100 + 105 = 205 To find the total number of cells required for a two dimensional array, we use the following formula : No. of elements = [(UB of I’st Dim. – LB of I’st Dim)+1] * [(UB of II’nd Dim. – LB of II’nd Dim)+1] Number of Cell = No. of elements x size For example, let us take an array LIST[20,5]. Suppose the size of each element is 2 unit, find out the total number of cells required for storage. UB of I’st Dim. = 20 LB of I’st Dim = 1 UB of II’nd Dim. = 5 LB of II’nd Dim = 1 No. of elements = [(UB of I’st Dim. – LB of I’st Dim)+1] * [(UB of II’nd Dim. – LB of II’nd Dim)+1] No. of elements = [(20-1)+1]*[(5-1)+1] = [19+1]*[4+1] = 20*5 = 100 Number of Cell = No. of elements x size = 100*2 = 200 1.7.2.2 Declaration of Two Dimensional Array : The syntax for the declaration of two dimensional array is : storage_class type_specifier array_name[index][index] For example, int list[3][4]; char color[30][21]; In the first declaration the list can be thought of as a table having three rows and four columns. Similarly, In the second declaration color is the array name; the array color in an array of 30 names of color, each name consists of not more than 20 characters, the last character being the string terminator ‘\0’. 1.7.2.3 Initialisation of Two Dimensional Array : If a two dimensional array definition includes the assignment of initial values, then care must be taken to the order in which the initial values are assigned to the array elements. The elements of the first row will be assigned first and then elements of the second rows will be assigned, and so on. For example, int list[3][4] = {10,20,30,40,50,60,70,80,90,100,110,120};

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

20 Data Structures

Here, the list can be thought of as a table having three rows and four columns. After the initialisation the array list will take the initial values as follows : list[0][0] = 10 list[0][1] = 20 list[0][2] = 30 list[0][3] = 40 list[1][0] = 50 list[1][1] = 60 list[1][2] = 70 list[1][3] = 80 list[2][0] = 90 list[2][1] = 100 list[2][2] = 110 list[2][3] = 120 For example, int list[3][4] = {10,20,30,40,50,60,70,80,90}; Here, the list can be thought of as a table having three rows and four columns. After the initialisation the array list will take the initial values as follows : list[0][0] = 10 list[0][1] = 20 list[0][2] = 30 list[0][3] = 40 list[1][0] = 50 list[1][1] = 60 list[1][2] = 70 list[1][3] = 80 list[2][0] = 90 list[2][1] = 0 list[2][2] = 0 list[2][3] = 0 The last three array elements of the third row will be zero. Forming groups of initial values enclosed within braces can alter the natural order in which the initial values are assigned. The values within an inner pair of braces will be assigned to the elements of a row, since the second subscript increases most rapidly. If there are too few values within a pair of braces, the remaining elements of that row will be assigned zeros. The number of values within each pair of braces cannot exceed the defined row size. For example, int list[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; Here, the four values in the first inner pair of braces are assigned to the array elements in the first row, the values in the second inner pair of braces are assigned to the array elements in the second row and so on. After the initialisation the array list will take the initial values as follows : list[0][0] = 1 list[0][1] = 2 list[0][2] = 3 list[0][3] = 4 list[1][0] = 5 list[1][1] = 6 list[1][2] = 7 list[1][3] = 8 list[2][0] = 9 list[2][1] = 10 list[2][2] = 11 list[2][3] = 12 Let us take another example in which we assign values only to the first three elements in each row. int list[3][4] = { {1,2,3}, {5,6,7}, {9,10,11} }; After the initialisation the array list will take the initial values as follows :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 21

list[0][0] = 1 list[0][1] = 2 list[0][2] = 3 list[0][3] = 0 list[1][0] = 5 list[1][1] = 6 list[1][2] = 7 list[1][3] = 0 list[2][0] = 9 list[2][1] = 10 list[2][2] = 11 list[2][3] = 0 The last element in each row is assigned a value of zero. For example, int list[3][4] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} }; In this case the compiler will generate the error message, since the number of values in each pair of braces exceeds the defined array size. Let us take an example in which we take the two dimensional array of character. char book[5][21] = { “Data”, “Structure”, “By”, “Sanjay”, “Jain” }; The first index indicates strings, “Data”, ”Structure” etc. and the second index specifies the characters in the string. Each string in the array consists of 21 characters including the string terminator. The number of characters may be less than the specified number in the array, the unfilled places will be filled in by ‘\0’; however, the number cannot exceed the maximum value of second index. 1.7.2.4 Various Operations of Two Dimensional Array : Let us suppose that book is a two dimensional linear array of strings. The following are the operations, which are performed on the two dimensional array : (i) Traversal Operation : Traversing is the process by which we can visit or access and process each element of array exactly once. For example, suppose we have a two-dimensional array of books in the computer memory and we want to visit each book of array book. (A) Algorithm : Following are the steps for traversal operation : (a) [Initialise the counter] Set (counter) i = 1 (b) [Traverse each element of the array] Repeat step (c) and (d) while i <= n (c) [Visit element and performs the operation] Apply operation on book[i]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

22 Data Structures

(d) [Increment counter] Set i := i +1 (e) End. (B) Equivalent C Function void traversal(char book[][30], int n) { int i=1; while(i<=n) { printf("Books name at %d place is:",i); printf("%s\n",book[i]); i++; } } (C) Implementation of Traversal Function : The following program array_two-dim_traversal.c shows the array implementation of the traversal function for the strings of books stored in two-dimensional array of the computer memory : /*array_two-dim_traversal.c*/ #include<stdio.h> #include<stdlib.h> void traversal(char[][30],int); void main() { int i=1,m; char book[10][30]; printf("This program performs the two dimensional array traversal operation on strings of books name!\n"); printf("How many books in the list:"); scanf("%d",&m); printf("!!Please enter the books!!\n"); while(i<=m) { printf("Input book name (%d) in a single string:",i); scanf("%s",&book[i]); i++; } traversal(book,m); } void traversal(char book[][30], int n) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 23

int i=1; printf("!!Entered books in the list after traversing the array are!!\n"); while(i<=n) { printf("Books name at %d place is:",i); printf("%s\n",book[i]); i++; } printf("\n"); } (D) Output of the Program This program performs the two dimensional array traversal operation on strings of books name! How many books in the list: 5 !!Please enter the books!! Input book name (1) in a single string: A.I. Input book name (2) in a single string: C.G. Input book name (3) in a single string: Networking Input book name (4) in a single string: T.O.C. Input book name (5) in a single string: S.E. !!Entered books in the list after traversing the array are!! Books name at 1 place is: A.I. Books name at 2 place is: C.G. Books name at 3 place is: Networking Books name at 4 place is: T.O.C. Books name at 5 place is: S.E. (ii) Insertion Operation : Insertion is the operation by which we can add books in the strings of books at the desired position. Following is the algorithm, which shows the insertion operation. (A) Algorithm : Following are the steps for insertion operation : (a) [Initialise the counter with the size of the array] Set (counter) i := n (b) [Traverse each element of the array until we find the desired position] Repeat step (c) and (d) while i >= position (c) [Move element downward] Set book[i+1] := book[i] (d) [Decrease counter] Set i := i –1 (e) [Insert element at the desired position] Set book[position] := item

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

24 Data Structures

(f) [Reset the array size] Set n = n+1 (g) [Return the new array size] return(n) (h) End. (B) Equivalent C Function int insertion(char book[][20], int n, int position, char item[]) { int i; i=n; while(i>=position) { strcpy(book[i+1],book[i]); i--; } strcpy(book[position],item); n= n+1; return n; } (C) Implementation of Insertion Function : The following program array_two-dim_insertion.c shows the array implementation of the insertion function for strings of books stored in the computer memory : /*array_two-dim_insertion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int insertion(char[][20],int,int,char[]); void display(char[][20],int); void main() { int i=1,n,position; char book[10][20],item[20]; printf("This program performs the two dimensional array insertion operation on strings of books!\n"); printf("How many books in the array:"); scanf("%d",&n); printf("!!Please enter the books as a whole string!!\n"); while(i<=n) { printf("Input book name (%d) in a single string:",i); scanf("%s",&book[i]); i++; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 25

display(book,n); printf("Enter the posititon where we want to add a new book:"); scanf("%d",&position); printf("Please enter the book name for the position:"); scanf("%s",&item); n = insertion(book,n,position,item); display(book,n); } void display(char book[][20], int n) { int i=1; printf("!!Entered Books in the list are!!\n"); while(i<=n) { printf("Book name at %d place is:",i); printf("%s\n",book[i]); i++; } printf("\n"); } int insertion(char book[][20], int n, int position, char item[]) { int i; i=n; while(i>=position) { strcpy(book[i+1],book[i]); i--; } strcpy(book[position],item); n= n+1; return n; } (D) Output of the Program This program performs the two dimensional array insertion operation on strings of books! How many books in the array: 4 !!Please enter the books as a whole string!! Input book name (1) in a single string: D.S. Input book name (2) in a single string: A.I. Input book name (3) in a single string: Networking Input book name (4) in a single string: Compiler

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

26 Data Structures

!!Entered Books in the list are!! Book name at 1 place is: D.S. Book name at 2 place is: A.I. Book name at 3 place is: Networking Book name at 4 place is: Compiler Enter the posititon where we want to add a new book: 2 Please enter the book name for the position: T.O.C. !!Entered Books in the list are!! Book name at 1 place is: D.S. Book name at 2 place is: T.O.C. Book name at 3 place is: A.I. Book name at 4 place is: Networking Book name at 5 place is: Compiler (iii) Deletion Operation : The following is the algorithm, which shows the deletion operation in the two-dimensional array book of strings of books stored in memory. (A) Algorithm : Following are the steps for deletion operation : (a) [Initialise the counter with the size of the array and assign the desired position data value to item] Set (counter) i := n & item := book[position] (b) [Update the list] Repeat step (c) and (d) while (position <= n) (c) [Move element upward] Set book[position] := book[position+1] (d) [Increase counter] Set position := position +1 (e) [Reset the array size] Set n = n-1 (f) [Return the new array size] return(n) (g) End. (B) Equivalent C Function int deletion(char book[][20], int n, int position) { int i; char item[20]; i=n; strcpy(item,book[position]); printf("Deleted book from the position %d is : %s\n", position,item); while(position<=n) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 27

strcpy(book[position],book[position+1]); position++; } n= n-1; return n; } (C) Implementation of Deletion Function : The following program array_two-dim_deletion.c shows the array implementation of the deletion function for strings of books stored in the computer memory : /*array_two-dim_deletion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int deletion(char[][20],int,int); void display(char[][20],int); void main() { int i=1,n,position; char book[10][20]; printf("This program performs the two dimensional array deletion operation on strings of books!\n"); printf("How many books in the array:"); scanf("%d",&n); printf("!!Please enter the books as a whole string!!\n"); while(i<=n) { printf("Input book name (%d) in a single string:",i); scanf("%s",&book[i]); i++; } display(book,n); printf("Enter the position from where we want to delete a book name:"); scanf("%d",&position); n = deletion(book,n,position); display(book,n); } void display(char book[][20], int n) { int i=1; printf("!!Entered Books in the list are!!\n"); while(i<=n)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

28 Data Structures

{ printf("Book name at %d place is:",i); printf("%s\n",book[i]); i++; } printf("\n"); } int deletion(char book[][20], int n, int position) { int i; char item[20]; i=n; strcpy(item,book[position]); printf("Deleted book from the position %d is:%s\n",position,item); while(position<=n) { strcpy(book[position],book[position+1]); position++; } n= n-1; return n; } (D) Output of the Program This program performs the two dimensional array deletion operation on strings of books! How many books in the array: 5 !!Please enter the books as a whole string!! Input book name (1) in a single string: D.S. Input book name (2) in a single string: A.I. Input book name (3) in a single string: C.G. Input book name (4) in a single string: Networking Input book name (5) in a single string: T.O.C !!Entered Books in the list are!! Book name at 1 place is: D.S. Book name at 2 place is: A.I. Book name at 3 place is: C.G. Book name at 4 place is: Networking Book name at 5 place is: T.O.C Enter the position from where we want to delete a book name: 4 Deleted book from the position 4 is : Networking !!Entered Books in the list are!!

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 29

Book name at 1 place is: D.S. Book name at 2 place is: A.I. Book name at 3 place is: C.G. Book name at 4 place is: T.O.C 1.7.3 Triangular Array : A triangular or three-dimensional array can be compared with a book. In three-dimensional array, three dimensions can be termed as row, column and page. Number of rows = x (number of elements in a column) Number of columns = y (number of elements in a row) Number of pages = z Assume that aijk is an element in i-th row, j-th column and k-th page. 1.7.3.1 Storage of Three Dimensional Array in Memory : Storing a three-dimensional array means, storing the pages one by one. Storing of pages is same as storing a two-dimensional array. To find the actual address of an element aijk in three-dimensional array we use the following formula : Address(aijk) = Number of elements in first(k –1) pages +Number of elements in k-th page up to(i –1) rows +Number of elements in k-th page, (in i-th row up to j-th column) = xy(k –1) + (i –1)y + j

1.8 STRUCTURE
In previous topic we studied about the array, which is a data structure whose elements are all of the same type. We now turn our attention to the structure, which is a data structure whose individual elements can differ in data types. These individual elements of a structure are called as structure members. So, the structure may contain different types of members like integer, character and float. All the members of the structure are logically related. Let us take an example of telephone list of all the users of BSNL in Gwalior City. The list contains the following information about the users : • Name • Telephone_Number • Profession • Address This telephone list of users can be represented with the help of the structure. 1.8.1 Declaration of Structure : The composition of a structure may be defined as follows :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

30 Data Structures

struct tag_name { data_type member1; data_type member2; …. data_type memberN; } Where struct is keyword, tag_name is a name that identifies structures of this type and member1, member2, …memberN, are individual member declarations. The individual members can be ordinary variables, pointers, arrays or other structures. Once the composition of the structure has been defined, individual structure-type variables can be declared as follows : storage-class struct tag_name var1, var2, …varN; Where storage-class is an optional storage class specifier, struct is required keyword, tag_name is the name that appear in the structures type declaration, and var1, var2, …varN are structure variables of type tag_name. For example, the list of users of BSNL in Gwalior can be declared as : struct Telephone_List { char Name[30]; int Telephone_Number[6]; char Profession[30]; char Address[80]; } struct Telephone_List Telephone; Where Telephone is a variable of type Telephone_List. It is possible to combine the declaration of the structure composition with that of the structure variables as follows : storage-class struct tag_name { data_type member1; data_type member2; …. data_type memberN; } var1,var2,…varN; For example, the list of users of BSNL in Gwalior can be declared as : struct Telephone_List {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 31

char Name[30]; int Telephone_Number[6]; char Profession[30]; char Address[100]; }Telephone; Where Telephone is a variable of type Telephone_List. It is possible to assign initial values to the members of the structure variable, in much the same manner as the elements of the array. The initial values must appear in the order in which they will be assigned to their corresponding structure members, enclosed in braces and separated by commas. The syntax of this is : stroage-class struct tag_name var1 = {value1,value2, …, valueN}; Where value1, value2, …, valueN refers to the values of the first member, second member and so on, respectively. 1.8.2 Processing a Structure : The members of a structure are usually processed individually, as separate entities. Therefore, we must be able to access the individual structure members. A structure member can be accessed by writing : stru_var.member Where stru_var refers to the name of a structure-type variable, and member refers to the name of a member within the structure. The period (.) is the separator between the structure-type variable and member. For example, in the list of users of BSNL in Gwalior the individual members can be accessed as : Telephone_List.Name; Telephone_List.Telephone_Number; Telephone_List.Profession; Telephone_List.Address; 1.8.3 Implementation of Structure : The following program structure.c shows the structure implementation of the telephone list of the users of the BSNL in Gwalior City : /*structure.c*/ #include<stdio.h> /* Structure declaration for telephone list of the users */ struct Telephone_list { char Name[30]; int Telephone_No[6]; char Profession[30]; char Address[80]; }Tele[100];

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

32 Data Structures

void main() { int i,n; printf("This program maintains the telephone list of the users of the BSNL in Gwalior city!!!\n"); printf("Please enter how many records we want in the list:\n"); scanf("%d",&n); printf("Please enter the information of the users\n"); for(i=0;i<n;i++) { printf("Name:"); fflush(stdin); gets(Tele[i].Name); printf("\nTelephone Number:"); scanf("%d",Tele[i].Telephone_No); printf("\nProfession:"); fflush(stdin); gets(Tele[i].Profession); printf("\nAddress:"); fflush(stdin); gets(Tele[i].Address); fflush(stdin); } printf("\n List of the users"); printf("\n ###################\n"); for(i=0;i<n;i++) { printf("Name:%s",Tele[i].Name); printf("\nTelephone Number:%d",Telephone[i].Tele_No); printf("\nProfession:%s",Tele[i].Profession); printf("\nAddress:%s",Tele[i].Address); } printf(“\n\n”); } Output of the Program This program maintains the telephone list of the users of the BSNL in Gwalior city!!! Please enter how many records we want in the list: 2 Please enter the information of the users Name: Sanjay Jain Telephone Number: 421403

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 33

Profession: Lecturer Address: C/o. Rajendra Jain, Shinde Ki Chhawni, Lashker, Gwl. Name: Amit Jain Telephone Number: 230091 Profession: Student Address: Hanuman Ghati, Lashker, Gwalior !!! List of the users !!! ################### Name: Sanjay Jain Telephone Number: 421403 Profession: Lecturer Address: C/o. Rajendra Jain, Shinde Ki Chhawni, Lashker, Gwl. Name: Amit Jain Telephone Number: 230091 Profession: Student Address: Hanuman Ghati, Lashker, Gwalior

1.9. CHARACTER STRINGS
A character string is simply a number of literal characters that are combined under concatenation to form a data structure, which is more complex than a simple character element. The number of characters in a string is called its length. The string with zero characters is called the empty string or the null string. Enclosing their characters in single quotation marks will denote strings. For example, ‘RAJ KAMAL’ ‘LESS THAN’ 1.9.1 Storing Strings : Strings can be stored in three types of structure : (i) Fixed Length Structures : In this structure, each line is viewed as a record, where all records have the same length, i.e., where each record accommodates the same number of characters. We will assume that our records have length 80 unless otherwise stated or implied. (ii) Variable Length with Fixed Maximum : Although strings may be stored in fixed length memory locations, there are advantages in knowing the actual length of each string. The storage of variable length strings in memory cells with fixed lengths can be done in two ways : (a) one can use a marker, such as two dollar sign($$), to signal the end of the string, (b) one can list the length of the string, as an additional item in the pointer array. (iii) Linked Structure : By a linked list, we mean a linearly ordered sequence of memory cells, called nodes, where each node contains an item, called a link, which points to the next node in the list.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

34 Data Structures

Strings may be stored in linked list as follows. Each memory cell is assigned one character or a fixed number of characters, and a link contained in the cell gives the address of the cell containing the next character or group of characters in the string. 1.9.2 String Operations : The following are the operations which can be used for string processing : (i) Substring : A string X is called a sub string of a string S if there exist strings Y and Z such that : S = Y // X // Z SUBSTRING(string, initial, length) (ii) Indexing : Indexing, also called pattern matching, refers to finding the position where a string pattern P first appears in a given string text T. INDEX(text, pattern) If the pattern P does not appear in the text T, then INDEX is assigned the value 0. The argument “text” and “pattern” can be either string constants or string variables. (iii) Concatenation : Let S1 and S2 be strings. The string consisting of the characters of S1, followed by the characters of S1 is called the concatenation of S1 and S2. It will denoted by S1//S2. (iv) Length : The number of characters in a string is called its length. LENGTH(string)

1.10 POINTERS
A pointer is a variable, which may contain the address of another variable. All variables in C except variables of type register, have an address. The address is the location where the variable exists in memory. Pointers are used to access elements of array, pass arguments to a function by reference in order to modify the original values of the arguments, transmit arrays and strings to functions, pass functions as arguments to functions, simplify representation of multi-dimensional arrays, allocate memory spaces and create data structures. It is also applicable to all basic types of data and derived data types like: structures, unions, functions and files. 1.10.1 Declaration of Pointers : We must use an asterisk(*) in front of a variable to declare the variable to be a pointer. This identifies the fact that the variable is a pointer. The data type that appears in the declaration refers to the object of the pointer, i.e., the data item that is stored in the address represented by the pointer, rather than the pointer itself. Thus, a pointer declaration may be written as :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 35

type_specifier *pointer_name; Where pointer_name is the name of the pointer variable and type_specifier refers to the data type of the pointer object. For example, char *p; Where p is a pointer of type char. So, p may contain the address of a variable of type char. 1.10.2 Assignment of Valid Address to Pointers : Declaration of a pointer variable is not enough unless a specific address is placed in it. Because without that, pointer will be pointing to some memory location which may contain garbage or part of a compiler. Declaration reserves memory spaces for the pointer not for the object it points. For a valid and operational pointer variable, it must be assigned address of a variable. We can obtain the address of a simple variable by using the unary operator &. For example, char c; char *p; p = &c; Now p contains the address of the variable c. It is important that the type of the variable and the type of the pointer be the same. 1.10.3 Accessing the Pointers Object : Once the pointer is assigned the address of the variable to which it points, the pointer and the variable are accessible. The indirection operator(*) returns the value of the variable to which the pointer points. The value of the variable is indirectly accessed through *. If the pointer value is invalid, the indirection operator will return invalid value. The indirection operator specifies the contents of a variable, which has a distinct address like A or A[20]; it cannot be applied to any expression. Let us take an example for showing the declaration of pointer, assignment of valid address to a pointer and accessing the pointer object. The following program pointer_processing.c shows the concepts in processing of pointer variables : /*pointer_processing.c*/ #include<stdio.h> void main() { int A = 20; char B = 'P'; double C = 12.24; int *P1; char *P2; double *P3;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

36 Data Structures

printf("The following program shows the processing concepts of pointer variables!!!!\n"); printf("Value of pointer(P1) without assigning address and without indirection operator P1=%x\n",P1); printf("Value of pointer(P1) without assigning address P1=%x\n",*P1); P1 = &A; printf("Value of pointer(P1) without indirection operator=%x\n",P1); printf("Value of pointer(P1) P1=%d\n",*P1); printf("Value of pointer(P2) without assigning address and without indirection operatorP2=%x\n",P2); printf("Value of pointer(P2) without assigning address P2=%x\n",*P2); P2 = &B; printf("Value of pointer(P2) without indirection operator P2=%x\n",P2); printf("Value of pointer(P2) P2=%c\n",*P2); printf("Value of pointer(P3) without assigning address and without indirection operator P3=%x\n",P3); printf("Value of pointer(P3) without assigning address P3=%x\n",*P3); P3 = &C; printf("Value of pointer(P3) without indirection operator P3=%x\n",P3); printf("Value of pointer(P3) P3=%f\n",*P3); } Output of the Program The following program shows the processing concepts of pointer variables!!!! Value of pointer(P1) without assigning address and without indirection operator P1=cccccccc Value of pointer(P1) without assigning address P1=c5b6c5b0 Value of pointer(P1) without indirection operator=65fdf4 Value of pointer(P1) P1=20 Value of pointer(P2) without assigning address and without indirection operatorP2=cccccccc Value of pointer(P2) without assigning address P2=ffffffb0 Value of pointer(P2) without indirection operator P2=65fdf0 Value of pointer(P2) P2=P Value of pointer(P3) without assigning address and without indirection operatorP3=cccccccc

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 37

Value of pointer(P3) without assigning address P3=c5b6c5b0 Value of pointer(P3) without indirection operator P3=65fde8 Value of pointer(P3) P3=12.240000

1.11 DYNAMIC MEMORY MANAGEMENT
Language C provides a powerful facility for processing pointers and standard functions for requesting additional memory and for releasing memory during program execution. For dynamic allocation of memory, we can use dynamic variables, which are created during program execution. Since dynamic variables do not exist while the program is compiled, they can not be assigned names while it is being written. The only way to access dynamic variables is by using pointers. Once it is created, however, a dynamic variable does contain data and must have a type like any other variable. The creation and destruction of dynamic variables is done with standard functions in C. If p has been declared as a pointer to type data_type, then the statement : p = (data_type*)malloc(sizeof(data_type)); creates a new dynamic variable of type data_type and assigns its location to the pointer p. Where data_type denotes the types of items. The function malloc allocates a block of memory and returns a pointer to that block of memory. The number of bytes occupied by a variable of data_type is calculated by the sizeof operator. If there is insufficient memory to create the new dynamic variable, malloc will fail and will return NULL. When a dynamic variable is no longer needed, the function call : free(p); returns the space used by the dynamic variable to which p points to the system. After the function free(p) is called, the pointer variable p is undefined and so can not be used until it is assigned a new value. Let us take an example for showing the allocation and deallocation of memory. The program pointer_allocation.c shows this process : /*pointer_allocation.c*/ #include<stdio.h> #include<malloc.h> #include<stdlib.h> void main() { int *p,i; printf("The following program shows the dynamic allocation of pointer variables!!!!\n"); p = (int*)malloc(10*(sizeof(int)));

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

38 Data Structures

printf("ADDRESS\t INFORMATION\n"); for (i =0; i <10; i++) { *(p+i) = 20; printf("%x",(p+i)); printf("\t\t%d",*(p+i)); printf("\n"); } free(p); } Output of the Program The following program shows the dynamic allocation of pointer variables!!!! ADDRESS INFORMATION 780e90 20 780e94 20 780e98 20 780e9c 20 780ea0 20 780ea4 20 780ea8 20 780eac 20 780eb0 20 780eb4 20

1.12 POINTER TO STRUCTURE
A pointer can hold the address of an aggregate data type such as structure. Similar to pointers to basic data types, pointer to aggregate type can be initialised with address of statically or dynamically created information items. We can declare a pointer variable for a structure by writing : type_specifier *pointer_name; Where type_specifier is a data type, which identifies the composition of the structure and pointer_name represents the name of the pointer variable. The beginning address of a structure can be accessed in the same manner as any other address, through the use of the address(&) operator. Thus if var represents a structure type variable, then &var represents the starting address of that variable. We can assign the beginning address of a structure variable to the pointer variable by writing : poniter_name = &var The structure variable and pointer declaration can be combined with the structure declaration by writing :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 39

struct { data_type member1; data_type member2; …. data_type memberN; }var *pointer_name; pointer_name = &var; Let us again discuss the same example as discussed in the case of structure . The list of users of BSNL in Gwalior can be declared as : struct { char Name[30]; int Telephone_Number[6]; char Profession[30]; char Address[100]; }Telephone_list, *Telephone; Telephone = &Telephone_list; An individual structure member can be accessed in terms of its corresponding pointer variable by writing : pointer_name->member Where pointer_name refers to a structure type pointer variable and the operator(->) is comparable to the period(.) operator as discussed in structure. For example, in the list of users of BSNL in Gwalior the individual members can be accessed as : Telephone->Name; Telephone->Telephone_Number; Telephone->Profession; Telephone->Address; 1.12.1 Implementation of Pointer to Structure : The following program pointer_to_structure.c shows the pointer to structure implementation of the telephone list of the users of the BSNL in Gwalior City : /*pointer_to_structure.c*/ #include<stdio.h> /* Pointer to structure declaration for telephone list of the users */ struct { char Name[30]; int Telephone_No[6]; char Profession[30]; char Address[80]; }Telephone, *Tele = &Telephone;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

40 Data Structures

void main() { int i,n; printf("This program maintains the telephone list of the users of the BSNL in Gwalior city!!!\n"); printf("Please enter how many records we want in the list:\n"); scanf("%d",&n); printf("Please enter the information of the users\n"); for(i=0;i<n;i++) { printf("Name:"); fflush(stdin); gets(Tele->Name); printf("\nTelephone Number:"); scanf("%d",&Tele->Telephone_No); printf("\nProfession:"); fflush(stdin); gets(Tele->Profession); printf("\nAddress:"); fflush(stdin); gets(Tele->Address); fflush(stdin); } printf("\n List of the users"); printf("\n ###################\n"); for(i=0;i<n;i++) { printf("Name:%s",Tele->Name); printf("\nTelephone Number:%d",Tele->Telephone_No); printf("\nProfession:%s",Tele->Profession); printf("\nAddress:%s",Tele->Address); } printf(“\n\n”); } Output Of the Program This program maintains the telephone list of the users of the BSNL in Gwalior City!!! Please enter how many records we want in the list: 2 Please enter the information of the users: Name: Sanjay Jain Telephone Number: 421403 Profession: Lecturer Address: C/o. Rajendra Jain, Shinde Ki Chhawni, Lashker, Gwl.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Prerequisite 41

Name: Amit Jain Telephone Number: 230091 Profession: Student Address: Hanuman Ghati, Lashker, Gwalior List of the users ################### Name: Sanjay Jain Telephone Number: 421403 Profession: Lecturer Address: C/o. Rajendra Jain, Shinde Ki Chhawni, Lashker, Gwl. Name: Amit Jain Telephone Number: 230091 Profession: Student Address: Hanuman Ghati, Lashker, Gwalior

EXERCISE
Q.1. Write a function that counts number of vowels in a given text. Q.2. Write a function that counts number of words in a text and also counts the words of different types. Q.3. Write a function that inserts a sub-string in a string somewhere in the middle. Q.4. Write a program to access number of students in a class using pointers to structure. Q.5. Write a program to implement a structure for the following fields : Employee’s Name Designation Department Address City Telephone Number Q.6. Write a function that reads a string and transfers its reverse to another pointer variable.

**

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

2

LNIKED LIST, STACK AND QUEUE

2.1 INTRODUCTION
This chapter encompasses: single linked list, implentation of single linked using arrays, implementation of linked list using dynamic memory allocation, circular linked list, josephus problem, doubly linked list, polynomial manipulation using linked list and representation of sparse matrices. It includes stacks, their array and linked implementation, multiple stack using single array and their implementation. It also covers conversion of expressions from infix to postfix notations using stack, evaluation of postfix expression, recursion with their types, examples, advantages and disadvantages. Queues with their array and linked implementation, circular queues and its implementation, deques with their implementation, priority queues and simulation problem are also covered in this chapter. At the end of the chapter the exercise is given.

2.2 SINGLE LINKED LIST
A single linked list or simply a list is a linear collection of ordered data objects of the same data type. Real life events such as people waiting to purchase ticket at a railway reservation counter may be implemented using list structures. In the computer science, lists are extensively used in database management systems, in process management, in operating system etc. A list can be implemented statically or dynamically using an array index or pointers, respectively. 2.2.1 Contiguous or Array Implementation of Linked List : It is the simplest implementation. Its size is fixed and allocated at compilation time. All the elements in an array are stored in contiguous memory locations. Large number of operations are performed through array implementation of list. A list can be implemented as an array, as follows : The first element of a list is called head and the last element is called the tail of list. The next element to the head of the list is called its successor. The previous element to the tail of the list is called its predecessor. The elements in a list are tied together by their successorpredecessor relationships. Let us take an example for showing the array implementation of linked list. Consider the list of names of some countries as shown in figure 2.1. We may have an array country declared as : country[0..MAX-1] and fix its size as 10.
(42)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 43

country[0] country[1] country[2] country[3] country[4] country[5] country[6] country[7] country[8] country[9]

India Nepal Japan China Magnolia

Head of the list

Tail of the list

Allocated but not used

Fig. 2.1 Array Static Implementation of a List of Countries

The predecessor of country[0] is NILL, country[4]is the tail of the list and has no successor. Since the elements are stored sequentially, any element in the list can be accessed through its index. 2.2.2 Operations of Linked List : Following are the basic operations, which can be performed on a linked list : (i) Create a list. (ii) Traversal of a list. (iii) Search for an element from a list. (iv) Retrieve an element from a list. (v) Add an element at a specified location of a list. (vi) Delete an element from a list. (vii) Sort a list. (i) Creation and Traversal Operations of the Linked List : Creation and traversing is the process by which we can create a list and accessing and processing each element of list exactly once. For example, suppose we have a list of country in the computer memory as shown in figure 2.1. We want to create the list country and visit each element of the list country. (A) Algorithm : Following are the steps for creation and traversal operations of a linked list : (a) [Initialise the counter] Set (counter) i = 0 (b) [Create the list] Repeat step (c) and (d) while (i < n) (c) [Read the element] Read country[i] (d) [Increment counter] Set i := i +1 (e) [Again initialise the counter by zero] Set (counter) i =0

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

44 Data Structures

(f) [Traverse each element of the list] Repeat step (g) and (h) while (i < n) (g) [Visit element and perform the operation] Apply operation to country[i] (h) [Increment counter] Set i := i +1 (i) End. (B) Equivalent C Function void create_traversal(char country[][30], int n) { int i=0; printf("!!Please create the list of countries!!\n"); while(i<n) { printf("Enter country for the %d:",i); scanf("%s",&country[i]); i++; } printf("!!Entered countries in the list after traversing the list are!!\n"); i=0; while(i<n) { printf("country at position %d is:",i); printf("%s\n",country[i]); i++; } } (C) Implementation of Creation and Traversal Operations of the Linked List : The following program list_create_traversal.c shows the array implementation of the creation and traversal operations for the list of countries stored in the computer memory : /*list_create_traversal.c*/ #include<stdio.h> #include<stdlib.h> void create_traversal(char[][30], int); void main() { int i=0,n; char country[100][30]; printf("This program performs the creation and traversal operations on the list of countries!\n"); printf("How many countries in the list:");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 45

scanf("%d",&n); create_traversal(country, n); } void create_traversal(char country[][30], int n) { int i=0; printf("!!Please create the list of countries!!\n"); while(i<n) { printf("Enter country for the %d:",i); scanf("%s",&country[i]); i++; } printf("!! Entered countries in the list after traversing the list are!!\n"); i=0; while(i<n) { printf("country at position %d is:",i); printf("%s\n",country[i]); i++; } printf("\n"); } (D) Output of the Program This program performs the creation and traversal operations on the list of countries! How many countries in the list: 5 !!Please create the list of countries!! Enter country for the 0: India Enter country for the 1: China Enter country for the 2: Nepal Enter country for the 3: Mangolia Enter country for the 4: Bhutan !!Entered countries in the list after traversing the list are!! country at position 0 is: India country at position 1 is: China country at position 2 is: Nepal country at position 3 is: Mangolia country at position 4 is: Bhutan (ii) Searching and Retrieving an Element from the Linked List : Searching and retrieving an element is the process by which we can search and retrieve the element from the linked list.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

46 Data Structures

For example, suppose we have a list of country in the computer memory as shown in figure 2.1. We want to search the desired country in the list of countries and retrieve the same from the list. (A) Algorithm : Following are the steps for searching and retrieving an element from the linked list : (a) [Initialise the counter and set the flag to indicate whether the match is found or not] Set (counter) i = 0, match=0 (b) [Enter the item to be searched] Read item (c) [Search the desired item] Repeat step (d) and (e) while (i < n) (d) [compare the desired item with each item of the list] If(country[i] == item) then print desired item is found in the list, set match=1 and break (e) [Increment counter] Set i := i +1 (f) [Item is not found in the list] If(!match)then print desired item is not found in the list (g) End. (B) Equivalent C Function void search_retrieve(char country[][30], int n) { int i=0,match=0; char item[30]; printf("Enter the country to be searched.\n"); fflush(stdin); gets(item); while(i<n) { if(strcmp(country[i],item)==0) { printf("country position in the list is:%d\n",i); printf("The country is:%s\n",country[i]); match =1; break; } i++; } if(!match) printf("The country is not found in the list.\n"); printf("\n"); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 47

(C) Implementation of Searching and Retrieving an Element from the Linked List : The following program list_search_retrieve.c shows the array implementation of the searching and retrieving an element from the list of countries stored in the computer memory : /*list_search_retrieve.c*/ #include<stdio.h> #include<stdlib.h> void search_retrieve(char[][30], int); void main() { int i=0,n; char country[100][30]; printf("This program performs the searching and retrieve operations on the list of countries!\n"); printf("How many countries in the list:"); scanf("%d",&n); printf("!!Please create the list of countries!!\n"); while(i<n) { printf("Enter country for the %d:",i); scanf("%s",&country[i]); i++; } search_retrieve(country, n); } void search_retrieve(char country[][30], int n) { int i=0,match=0; char item[30]; printf("Enter the country to be searched.\n"); fflush(stdin); gets(item); while(i<n) { if(strcmp(country[i],item)==0) { printf("country position in the list is:%d\n",i); printf("The country is:%s\n",country[i]); match =1; break; } i++; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

48 Data Structures

if(!match) printf("The country is not found in the list.\n"); printf("\n"); } (D) Output of the Program This program performs the searching and retrieve operations on the list of countries!! How many countries in the list: 5 !!Please create the list of countries!! Enter country for the 0: India Enter country for the 1: England Enter country for the 2: Nepal Enter country for the 3: Indonesia Enter country for the 4: China Enter the country to be searched. Nepal country position in the list is: 2 The country is: Nepal This program performs the searching and retrieve operations on the list of countries!! How many countries in the list: 5 !!Please create the list of countries!! Enter country for the 0: India Enter country for the 1: Japan Enter country for the 2: Nepal Enter country for the 3: China Enter country for the 4: Malasiya Enter the country to be searched. England The country is not found in the list. (iii) Insertion Operation : Insertion is the operation by which we can add elements in the linked list of countries at the desired position. (A) Algorithm : Following are the steps for insertion operation in a linked list : (a) [Initialise the counter with the size of the array] Set (counter) i := n (b) [Traverse each element of the list until we find the desired position] Repeat step (c) and (d) while i >= position(desired position) (c) [Move element downward] Set country[i+1] := country[i] (d) [Decrease counter] Set i := i –1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 49

(e) [Insert element at the desired position] Set country[position] := item (f) [Reset the list size] Set n = n+1 (g) [Return the new list size] return(n) (h) End. (B) Equivalent C Function int insertion_list(char country[][20], int n, int position, char item[]) { int i; i=n; while(i>=position) { strcpy(country[i+1],country[i]); i--; } strcpy(country[position],item); n= n+1; return n; } (C) Implementation of Insertion Operation : The following program list_insertion.c shows the array implementation of the insertion operation for the list of countries stored in the computer memory : /*list_insertion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int insertion_list(char[][20],int,int,char[]); void display_list(char[][20],int); void main() { int i=1,n,position; char country[100][20],item[20]; printf("This program performs the insertion operation on the list of countries!\n"); printf("How many countries in the list:"); scanf("%d",&n); if(n>=100) { printf("List is full\n"); exit(0); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

50 Data Structures

printf("!!Please create the list of countries!!\n"); while(i<=n) { printf("Enter country for the %d:",i); fflush(stdin); gets(country[i]); i++; } display_list(country,n); printf("Enter the position where we want to add a new country:"); scanf("%d",&position); if(position >=(n+2) || position <0) { printf("Position is not avaiable\n"); exit(0); } printf("Please enter the country for the position:"); fflush(stdin); scanf("%s",&item); n = insertion_list(country,n,position,item); display_list(country,n); } void display_list(char country[][20], int n) { int i=1; printf("!!Entered countries in the list !!\n"); while(i<=n) { printf("country name at %d place is:",i); printf("%s\n",country[i]); i++; } printf("\n"); } int insertion_list(char country[][20], int n, int position, char item[]) { int i; i=n; while(i>=position) { strcpy(country[i+1],country[i]); i--; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 51

strcpy(country[position],item); n= n+1; return n; } (D) Output of the Program This program performs the insertion operation on the list of countries! How many countries in the list: 5 !!Please create the list of countries!! Enter country for the 1: India Enter country for the 2: Japan Enter country for the 3: England Enter country for the 4: China Enter country for the 5: Nepal !!Entered countries in the list !! country name at 1 place is: India country name at 2 place is: Japan country name at 3 place is: England country name at 4 place is: China country name at 5 place is: Nepal Enter the position where we want to add a new country: 3 Please enter the country for the position: Indonesia !!Entered countreis in the list !! country name at 1 place is: India country name at 2 place is: Japan country name at 3 place is: Indonesia country name at 4 place is: England country name at 5 place is: China country name at 6 place is: Nepal (iv) Deletion Operation : Deleting an element from the end of a list is simple but deleting an element from the desired position is difficult and requires moving all the element up-word to fill up the gap into the list. (A) Algorithm : Following are the steps for deletion operation of the linked list : (a) [Initialise the counter with the size of the list and assign the desired position data value to item] Set (counter) i := n & item := country[position] (b) [Update the list] Repeat step (c) and (d) while (position <= n) (c) [Move element upward] Set country[position] := country[position+1] (d) [Increase counter] Set position := position +1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

52 Data Structures

(e) [Reset the list size] Set n = n-1 (f) [Return the new list size] return(n) (g) End. (B) Equivalent C Function int deletion_list(char country[][20], int n, int position) { int i; char item[20]; i=n; strcpy(item, country[position]); printf("Deleted item from the position %d is : %d\n", position,item); while(position<=n) { strcpy(country[position], country[position+1]); position++; } n= n-1; return n; } (C) Implementation of Deletion Operation: The following program list_deletion.c shows the array implementation of the of deletion operation for the list of countries stored in the computer memory : /*list_deletion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int deletion_list(char[][20],int,int); void display_list(char[][20],int); void main() { int i=1, n,position; char country[100][20]; printf("This program performs the deletion operation on the list of countries!\n"); printf("How many countries in the list:"); scanf("%d",&n); printf("!!Please enter the country!!\n"); while(i<=n) { printf("Input country for the %d:",i);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 53

fflush(stdin); gets(country[i]); i++; } display_list(country,n); printf("Enter the position of the element, we want to delete from the list of countries:"); scanf("%d",&position); n = deletion_list(country,n,position); display_list(country,n); } void display_list(char country [][20], int n) { int i=1; printf("!!Entered countries in the list !!\n"); while(i<=n) { printf("country at position %d is:",i); puts(country[i]); i++; } printf("\n"); } int deletion_list(char country[][20], int n, int position) { int i; char item[20]; i=n; strcpy(item, country[position]); printf("Deleted country from the position %d is :%s\n", position, item); while(position<=n) { strcpy(country[position], country[position+1]); position++; } n= n-1; return n; } (D) Output of the Program This program performs the deletion operation on the list of countries! How many countries in the list: 4

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

54 Data Structures

!!Please enter the country!! Input country for the 1: India Input country for the 2: Japan Input country for the 3: China Input country for the 4: Nepal !!Entered countries in the list !! country at position 1 is: India country at position 2 is: Japan country at position 3 is: China country at position 4 is: Nepal Enter the position of the element, we want to delete from the list of country : 2 Deleted country from the position 2 is : Nepal !!Entered countries in the list !! country at position 1 is: India country at position 2 is: China country at position 3 is: Nepal 2.2.3 Drawback of Array Implementation of Linked List : The array implementation of our collection has one serious drawback. We must know the maximum number of items in our collection when we create it. This presents problems in programs in which this maximum number cannot be predicted accurately when the program starts up. Fortunately, we can use a structure called a linked list to overcome this limitation.

2.3 DYNAMIC IMPLEMENTATION OF LINKED LIST
The dynamic implementation of list is based on linked list. The linked list is a very flexible dynamic data structure, items may be added to it or deleted from it, as desired. A programmer need not worry about how many items a program will have to accommodate, this allows us to write robust programs, which require much less maintenance. A very common source of problems in program maintenance is the need to increase the capacity of a program to handle larger collections, even the most generous allowance for growth tends to prove inadequate over time. In a linked list, each item is allocated space, as it is added to the list. A link is kept with each item to the next item in the list. A linked list is a linear collection of data elements, called nodes, where the linear order is given by means of pointers, i.e., each node of the list has two components: (a) The first contains the item being stored in the list. (b) The second called link field contains a pointer to the next item in the list. The pointer of the last node contains a value called the null pointer denoted by X in the list, which is any invalid address. It indicates the

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 55

end of the list. The list also contains a pointer, which contains the address of the first node in the list, called as head. As items are added to a list, memory for a node is dynamically allocated. Thus, the number of items that may be added to a list is limited only by the amount of memory available. For example, fig. 2.2 shows a linked list structure of color names with 3 nodes, each node contain one item field(color name) and next node address field. There is also one list pointer variable called head, which contains the address of the first node in the list. The last node of the list contains NULL in the pointer field denoted by X.
Head RED BLUE PINK X

Fig. 2.2 Linked List

2.3.1 Declaration : The head points to the first node in the linked list and tail points to the last node of the linked list. The following is the declaration of the linked list. /*node declaration */ typedef struct node_tag{ char item[30]; struct node_tag *next; }node; /*linked list declaration */ typedef struct list_tag{ node *head; node *tail; }linked_list; 2.3.2 Operations of the Linked List : The following are the operations, which can be performed on linked list : (i) Create a list. (ii) Traversal of a list. (iii) Search for an element in a list. (iv) Display and count the number of elements in the list. (v) Add an element in the beginning of the list. (vi) Add an element before the specified element of a list. (vii) Add an element after the specified element of a list. (viii) Add an element at the end of the list. (ix) Delete an element at the beginning of the list. (x) Delete an element after the specified item from the list. (xi) Delete an element at the end of the list. (I) Creation and Traversal Opeations of a Linked List : Creation and traversal is the process by which we can create a list and accessing

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

56 Data Structures

and processing each element of the list exactly once. For example, suppose we have a list of colors in the computer memory as shown in figure 2.2. We want to create the list of colors and visit each color of the list. (i) Creation of Linked List : (A) Algorithm : Following are the steps for the creation of a linked list : (a) [Initialise the list empty] Set head=NULL, tail=NULL (b) [Allocate space to the newly created node] Set p = (node_type*)malloc(sizeof(node_type)) (c) [Copy the item to the newly created node] Set p->color = x (d) [Attach created node to the linked list] if(head ==NULL) then Set p->next = head, head = p, tail = p else Set p->next = NULL, tail->next = p, tail = p (e) End. (B) Equivalent C Function void create_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); if (LS->head==NULL) { p->next = LS->head; LS->head = p; LS->tail = p; } else { p->next = NULL; LS->tail->next = p; LS->tail = p; } } (ii) Traversal of Linked List: (A) Algorithm : Following are the steps for the traversal of a linked list : (a) [Traverse each element of the list] Repeat step (b) and (c) while (p!=NULL) (b) [Visit element and perform the operation] Print the value of element of the list using- p->color (c) [Increment counter]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 57

Set p = p->next (d) End. (B) Equivalent C Function void traversal_list(node_type *p) { while(p!=NULL) { printf("%s\n",p->color); p = p->next; } printf("\n"); } (iii) Implementation of Creation and Traversal Operations of the Linked List : The following program linked_list_create_traversal.c shows the pointer implementation of creation and traversal functions for the list of colors stored in the computer memory : /*linked_list_create_traversal.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> /*node declaration */ typedef struct node_tag { char color[20]; struct node_tag *next; }node_type; /*linked list declaration */ typedef struct list_tag { node_type *head,*tail; }linked_list; void initialise(linked_list * ); void traversal_list(node_type *); void create_list(linked_list *,char[]); void main() { char item[20]; linked_list *LS; initialise(LS); printf("This program performs the linked list creation and traversal operations on string of colors!\n");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

58 Data Structures

strcpy(item," "); while(strcmp(item,"END")!=0) { printf("Enter the color name(Please enter END for stop):\n"); scanf("%s",&item); if(strcmp(item,"END")!=0) create_list(LS,item); } printf("Entered color names in a linked list are:\n"); traversal_list(LS->head); } void initialise(linked_list *LS) { LS->head=NULL; LS->tail=NULL; } void create_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); if (LS->head==NULL) { p->next = LS->head; LS->head = p; LS->tail = p; } else { p->next = NULL; LS->tail->next = p; LS->tail = p; } } void traversal_list(node_type *p) { while(p!=NULL) { printf("%s\n",p->color); p = p->next; } printf("\n"); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 59

(iv) Output of the Program This program performs the linked list creation and traversal operations on string of colors! Enter the color name(Please enter END for stop): RED Enter the color name(Please enter END for stop): BLUE Enter the color name(Please enter END for stop): PINK Enter the color name(Please enter END for stop): YELLOW Enter the color name(Please enter END for stop): GREEN Enter the color name(Please enter END for stop): END Entered color names in a linked list are: RED BLUE PINK YELLOW GREEN (II) Searching and Counting the Number of Elements of the Linked List : In this operation, we search an element and count the total elements of the linked list. For example, suppose we have a list of colors in the computer memory as shown in figure 2.2. We want to search the desired color in the list of colors and count the total number of entered colors in the list. (i) Algorithm : Following are the steps for searching and counting the number of elements of the linked list : (a) [Initialise the counter for counting the number elements and set the flag to indicate whether the match is found or not] Set (counter) i = 0, match=0 (b) [Enter the item to be searched] Read item (c) [Search the desired item] Repeat step (d) while(p!=NULL) (d) [Compare the desired item with each item of the linked list] If(p->color == item) then print desired item is found in the linked list, Set match = 1 and p = p->next else Set p = p->next and i = i+1 (e) [Item is not found in the linked list]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

60 Data Structures

If(!match)then print desired item is not found in the linked list (f) [Print total elements in the linked list] print i (g) End. (ii) Equivalent C Function void search_count_list(node_type *p) { int i=0,match=0; char item[20]; printf("Enter the color to be searched:"); scanf("%s",&item); while(p!=NULL) { if(strcmp(p->color,item)==0) { printf("The color is found in the linked list and the color is:%s\n",p->color); match =1; p= p->next; } else { p = p->next; } i++; } if(!match) printf("The color is not found in the linked list.\n"); printf("The total number of elements in the linked list are :%d",i); printf("\n"); } (iii) Implementation of Searching and Counting Operations of the Linked List : The following program linked_list_search_count.c shows the pointer implementation of the searching and counting operations for the list of colors stored in the computer memory : /*linked_list_search_count.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h>

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 61

/*node declaration */ typedef struct node_tag { char color[20]; struct node_tag *next; }node_type; /*linked list declaration */ typedef struct list_tag { node_type *head,*tail; }linked_list; void initialise(linked_list * ); void display(node_type *); void create_list(linked_list *,char[]); void search_count_list(node_type *); void main() { char item[20]; linked_list *LS; initialise(LS); printf("This program performs the searching of and counting the number of elements in the linked list of colors!\n"); printf("!!Please create the list of colors!!\n"); strcpy(item," "); while(strcmp(item,"END")!=0) { printf("Enter the color name(Please enter END for stop):\n"); scanf("%s",&item); if(strcmp(item,"END")!=0) create_list(LS,item); } printf(“Entered color names in a linked list are:\n”); display(LS->head); search_count_list(LS->head); } void search_count_list(node_type *p) { int i=0,match=0; char item[20]; printf("Enter the color to be searched:"); scanf("%s",&item); while(p!=NULL)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

62 Data Structures

{ if(strcmp(p->color,item)==0) { printf("The color is found in the linked list and the color is:%s\n",p->color); match =1; p= p->next; } else { p = p->next; } i++; } if(!match) printf("The color is not found in the linked list.\n"); printf("The total number of elements in the linked list are :%d",i); printf("\n"); } void initialise(linked_list *LS) { LS->head=NULL; LS->tail=NULL; } void create_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); if (LS->head==NULL) { p->next = LS->head; LS->head = p; LS->tail = p; } else { p->next = NULL; LS->tail->next = p; LS->tail = p; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 63

void display(node_type *p) { while(p!=NULL) { printf("%s\n",p->color); p = p->next; } printf("\n"); } (iv) Output of the Program This program performs the searching of and counting the number of elements in the linked list of colors! !!Please create the list of colors!! Enter the color name(Please enter END for stop): RED Enter the color name(Please enter END for stop): GREEN Enter the color name(Please enter END for stop): YELLOW Enter the color name(Please enter END for stop): BULE Enter the color name(Please enter END for stop): PINK Enter the color name(Please enter END for stop): END Entered color names in a linked list are: RED GREEN YELLOW BLUE PINK Enter the color to be searched: YELLOW The color is found in the linked list and the color is : YELLOW The total number of elements in the linked list are : 5 (III) Insertion Operation in the Linked List : There are four ways, one can insert an element into the linked list. These are : (i) Insert an element in the beginning of the linked list. (ii) Insert an element before the specified element of a linked list. (iii) Insert an element after the specified element of a linked list. (iv) Insert an element at the end of the linked list. Let us consider the linked list of colors in the computer memory as shown in figure 2.2. We want to insert a color into the linked list of colors at a specified position. The following are the algorithms which can perform the insertion operation.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

64 Data Structures

(i) Insert an Element at the Beginning of the Linked List : (A) Algorithm : Following are the steps for insert an element at the beginning of the linked list : (a) [Allocate space to the newly created node] Set p = (node_type*)malloc(sizeof(node_type)) (b) [Copy the item to the newly created node] Set p[color] = x (c) [Attach created node at the beginning of the linked list] Set p[next] = head, head = p (d) End. (B) Equivalent C Function void insertion_beginning_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); p->next = LS->head; LS->head = p; } (ii) Insert an Element After the Specified Element of a Linked List : (A) Algorithm : Following are the steps for insert an element after the specified element of a linked list : (a) [Allocate space to the newly created node] Set p = (node_type*)malloc(sizeof(node_type)) (b) [Copy the item to the newly created node] Set p[color] = x (c) [Assign linked list head to the temporary pointer] Set pointer = head (d) [Read the element after which the new node is attach] Read item (e) [Repeat steps (f) and (g) while(pointer!=NULL) (f) [Compare each elements of the linked list to the element after which the new node is attach] If(pointer[color] == item) then Set p[next] = pointer[next], pointer[next] = p (g) [Now pointer point to the next node in the linked list] Set pointer = pointer[next] (h) End. (B) Equivalent C Function void insertion_after_list(linked_list *LS, char x[]) { char item[20]; node_type *p,*pointer;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 65

p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); pointer= LS->head; printf("Enter the name of color after which we want to insert the color:\n"); scanf("%s",&item); while(pointer!=NULL) { if(strcmp(pointer->color,item)==0) { p->next = pointer->next; pointer->next = p; } pointer = pointer->next; } } (iii) Insert an Element Before the Specified Element of a Linked List : (A) Algorithm : Following are the steps for insert an element before the specified element of a linked list : (a) [Allocate space to the newly created node] Set p = (node_type*)malloc(sizeof(node_type)) (b) [Copy the item to the newly created node] Set p[color] = x (c) [Assign linked list head to the temporary pointer] Set current = head (d) [Read the element before that the new node is attach] Read item (e) [Compare the head of the linked list to the element before that the new node is attach] If(current[color] == item) then the item is attach as the first node; Set p[next] =head, head = p (f) [Otherwise compare each element of the linked list to the element before that the new node is attach] Repeat steps (g) and (h) while(current!=NULL) (g) [Assign current pointer of the linked list to the pointer previous and increment current pointer tot he next node] Set previous = current, current = current[next] (h) [ Performs comparison] if(current[color] == item) then Set p[next] =current, previous[next] = p and break (i) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

66 Data Structures

(B) Equivalent C Function void insertion_before_list(linked_list *LS, char x[]) { char item[20]; node_type *p,*current,*previous; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); current= LS->head; printf("Enter the name of color before which we want insert the color:\n"); scanf("%s",&item); if(strcmp(current->color,item)==0) { p->next = LS->head; LS->head = p; } else { while(current!=NULL) { previous = current; current = current->next; if(strcmp(current->color,item)==0) { p->next = current; previous->next = p; break; } } } } (iv) Insert an Element at the End of the Linked List : (A) Algorithm : Following are the steps for insert an element at the end of the linked list : (a) [Allocate space to the newly created node] Set p = (node_type*)malloc(sizeof(node_type)) (b) [Copy the item to the newly created node] Set p[color] = x, p[next] = NULL (c) [Attach created node to the at the end of the linked list] If(tail ==NULL) then Set tail = p, head = tail else Set tail[next] = p, tail = p (d) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 67

(B) Equivalent C Function void insertion_end_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); p->next = NULL; if(LS->tail == NULL) { LS->tail = p; LS->head = LS->tail; } else { LS->tail->next = p; LS->tail = p; } } (v) Implementation of Insertion Operation of a Linked List : The program linked_list_insertion.c shows the pointer implementation of the insertion functions for the list of colors stored in the computer memory : /*linked_list_insertion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> /*node declaration */ typedef struct node_tag { char color[20]; struct node_tag *next; }node_type; /*linked list declaration */ typedef struct list_tag { node_type *head,*tail; }linked_list; void initialise(linked_list * ); void display(node_type *); void create_list(linked_list *,char[]); void insertion_beginning_list(linked_list *, char[]); void insertion_after_list(linked_list *, char[]); void insertion_before_list(linked_list *, char[]); void insertion_end_list(linked_list *, char[]);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

68 Data Structures

void main() { int choice; char item[20]; linked_list *LS; initialise(LS); printf("This program performs the insertion operations on a specified positions in a linked list of colors!\n"); printf("!!Please create the list of colors!!\n"); strcpy(item," "); while(strcmp(item,"END")!=0) { printf("Enter the color name(Please enter END for stop):\n"); scanf("%s",&item); if(strcmp(item,"END")!=0) create_list(LS,item); } printf("Entered colors in a linked list are:\n"); display(LS->head); printf("###############Menu#############\n"); printf("\n1: Insert an element in the beginning of the linked list."); printf("\n2: Insert an element before the specified element of a linked list."); printf("\n3: Insert an element after the specified element of a linked list."); printf("\n4: Insert an element at the end of the linked list."); printf("\n5: End. "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: { printf("Enter color to be added at beginning:\n"); scanf("%s",&item); insertion_beginning_list(LS,item); printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } case 2: {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 69

printf("Enter color to be added before the specified element :\n"); scanf("%s",&item); insertion_before_list(LS,item); printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } case 3: { printf("Enter color to be added after the specified element :\n"); scanf("%s",&item); insertion_after_list(LS,item); printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } case 4: { printf("Enter color to be added at the end of the linked list:\n"); scanf("%s",&item); insertion_end_list(LS,item); printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } case 5: printf("End."); return; } }while(choice!=5); } void initialise(linked_list *LS) { LS->head=NULL; LS->tail=NULL; } void create_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); if (LS->head==NULL) { p->next = LS->head;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

70 Data Structures

LS->head = p; LS->tail = p; } else { p->next = NULL; LS->tail->next = p; LS->tail = p; } } void insertion_beginning_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); p->next = LS->head; LS->head = p; } void insertion_after_list(linked_list *LS, char x[]) { char item[20]; node_type *p,*pointer; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); pointer= LS->head; printf("Enter the name of color after which we want insert the color:\n"); scanf("%s",&item); while(pointer!=NULL) { if(strcmp(pointer->color,item)==0) { p->next = pointer->next; pointer->next = p; } pointer = pointer->next; } } void insertion_before_list(linked_list *LS, char x[]) { char item[20]; node_type *p,*current,*previous; p = (node_type*)malloc(sizeof(node_type));

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 71

strcpy(p->color,x); current= LS->head; printf("Enter the name of color before which we want insert the color:\n"); scanf("%s",&item); if(strcmp(current->color,item)==0) { p->next = LS->head; LS->head = p; } else { while(current!=NULL) { previous = current; current = current->next; if(strcmp(current->color,item)==0) { p->next = current; previous->next = p; break; } } } } void insertion_end_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); strcpy(p->color,x); p->next = NULL; if(LS->tail == NULL) { LS->tail = p; LS->head = LS->tail; } else { LS->tail->next = p; LS->tail = p; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

72 Data Structures

void display(node_type *p) { while(p!=NULL) { printf("%s\n",p->color); p = p->next; } printf("\n"); } (vi) Output of the Program This program performs the insertion operations on specified positions in a linked list of colors! !!Please create the list of colors!! Enter the color name(Please enter END for stop): RED Enter the color name(Please enter END for stop): BLUE Enter the color name(Please enter END for stop): END Entered colors in the linked list are : RED BLUE ###############Menu############# 1: Insert an element in the beginning of the linked list. 2: Insert an element before the specified element of a linked list. 3: Insert an element after the specified element of a linked list. 4: Insert an element at the end of the linked list. 5: End. Please enter choice 1 Enter color to be added at beginning: PINK Entered colors in a linked list are: PINK RED BLUE Please enter choice 2 Enter color to be added before the specified element : YELLOW Enter the name of color before which we want insert the color: BLUE

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 73

Entered colors in a linked list are: PINK RED YELLOW BLUE Please enter choice 3 Enter color to be added after the specified element : GREEN Enter the name of color after which we want insert the color: RED Entered colors in a linked list are: PINK RED GREEN YELLOW BLUE Please enter choice 4 Enter color to be added at the end of the linked list: WHITE Entered colors in a linked list are: PINK RED GREEN YELLOW BLUE WHITE Please enter choice 5 End. (IV) Deletion Operation in the Linked List : There are three ways, one can delete an element into the linked list. These are : (i) Delete an element in the beginning of the linked list. (ii) Delete an element after the specified element of a linked list. (iii) Delete an element at the end of the linked list. Let us consider the linked list of colors in the computer memory as shown in figure 2.2. We want to delete a color into the linked list of colors at a specified position. The following are the algorithms which can perform the deletion operation.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

74 Data Structures

(i) Delete an Element at the Beginning of the Linked List : (A) Algorithm : (a) [Check for empty linked list] If(head == NULL) then list is empty and return (b) [Otherwise delete the top element from the linked list and update the link] item = head Print “deleted color from the linked list “,item head = head[next] (c) End. (B) Equivalent C Function void deletion_beginning_list(linked_list *LS) { char item[20]; strcpy(item,LS->head); LS->head = LS->head->next; printf("Deleted color from the linked list is:"); printf("%s\n",item); } (ii) Delete an Element After the Specified Element of a Linked List : (A) Algorithm : (a) [Check for empty linked list] If(head == NULL) then list is empty and return (b) [Otherwise enter the name of the color after which we want to delete the color] Read(item) pointer = head after = pointer[next] (c) [Search the item in the list and performs the deletion] Repeat steps (d) to (f) while(pointer !=NULL) (d) [Check the list for single item or for searched item is the last item] If(after == NULL) then the item after which the deletion is performs is the last item in the linked list, this operation is not possible. (e) [Otherwise compare the item and delete the desired item] If(strcmp(pointer[color],item) == 0) then print "Deleted color from the linked list is: after[color] pointer[next] = after[next] break (f) [Otherwise update the link] Set pointer = after after = after[next] (g) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 75

(B) Equivalent C Function void deletion_after_list(linked_list *LS) { char item[20]; node_type *after,*pointer; pointer = LS->head; printf("Enter the name of color after which we want to delete the color:\n"); scanf("%s",&item); after = pointer->next; while(pointer!=NULL) { if(after == NULL) { printf("The item after which the deletion performed, is the last item in the linked list, this operation is not possible!!!\n"); break; } if(strcmp(pointer->color,item) == 0) { printf("Deleted color from the linked list is:"); printf("%s\n",after->color); pointer->next = after->next; break; } else { pointer = after; after = after->next; } } } (iii) Delete an Element at the End of the Linked List : (A) Algorithm : (a) [Check for empty linked list] If(head == NULL) then list is empty and return (b) [Otherwise check the list contain single item] pointer = head If(pointer[next] == NULL) then Print “deleted color from the linked list “,pointer[color] head = NULL (c) [Otherwise search the item in the list and performs the deletion]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

76 Data Structures

Repeat steps (d) to (f) while(pointer !=NULL) Set previous = pointer, pointer = pointer[next] (e) [Delete the color from the end of the end of the list] If(pointer[next] == NULL) then print "Deleted color from the linked list is:" previous[next][color] (f) Set previous->next = NULL (g) [Release memory] free(pointer) (h) End. (B) Equivalent C Function void deletion_end_list(linked_list *LS) { node_type *pointer,*previous; pointer = LS->head; if(pointer->next == NULL) { printf("Deleted color from the linked list is:"); printf("%s\n",pointer->color); LS->head = NULL; } else { while(pointer!=NULL) { previous = pointer; pointer = pointer->next; if(pointer->next == NULL) { printf("Deleted color from the linked list is:"); printf("%s\n",previous->next->color); break; } } previous->next = NULL; } free(pointer); } (iv) Implementation of Deletion Operations of a Linked List : The program linked_list_deletion.c shows the pointer implementation of the deletion functions for the list of colors stored in the computer memory : (d)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 77

/*linked_list_deletion.c*/ #include<stdio.h> #include<stdlib.h> #include<string.h> /*node declaration */ typedef struct node_tag { char color[20]; struct node_tag *next; }node_type; /*linked list declaration */ typedef struct list_tag { node_type *head,*tail; }linked_list; void initialise(linked_list * ); void display(node_type *); void create_list(linked_list *,char[]); void deletion_beginning_list(linked_list *); void deletion_after_list(linked_list *); void deletion_end_list(linked_list *); void main() { int choice; char item[20]; linked_list *LS; initialise(LS); printf("This program performs the deletion operations on a specified positions in a linked list of colors!\n"); printf("!!Please create the list of colors!!\n"); strcpy(item," "); while(strcmp(item,"END")!=0) { printf("Enter the color name(Please enter END for stop):\n"); scanf("%s",&item); if(strcmp(item,"END")!=0) create_list(LS,item); } printf("Entered colors in a linked list are:\n"); display(LS->head); printf("###############Menu#############\n"); printf("\n1: Delete an element in the beginning of the linked list.");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

78 Data Structures

printf("\n2: Delete an element after the specified element of a linked list."); printf("\n3: Delete an element at the end of the linked list."); printf("\n4: End. "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: { if (LS->head==NULL) { printf("Linked list is empty!!!\n"); continue; } else { deletion_beginning_list(LS); if (LS->head==NULL) { printf("Linked list is empty!!!\n"); continue; } else { printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } } } case 2 : { if (LS->head==NULL) { printf("Linked list is empty!!!\n"); continue; } else {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 79

deletion_after_list(LS); printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } } case 3 : { if (LS->head==NULL) { printf("Linked list is empty!!!\n"); continue; } else { deletion_end_list(LS); if (LS->head==NULL) { printf("Linked list is empty!!!\n"); continue; } else { printf("Entered colors in a linked list are:\n"); display(LS->head); continue; } } } case 4 : printf("End."); return; } }while(choice!=4); } void initialise(linked_list *LS) { LS->head=NULL; LS->tail=NULL; } void create_list(linked_list *LS, char x[]) { node_type *p; p = (node_type*)malloc(sizeof(node_type));

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

80 Data Structures

strcpy(p->color,x); p->next = NULL; if (LS->head==NULL) { p->next = LS->head; LS->head = p; LS->tail = p; } else { p->next = NULL; LS->tail->next = p; LS->tail = p; } } void deletion_beginning_list(linked_list *LS) { char item[20]; strcpy(item,LS->head); LS->head = LS->head->next; printf("Deleted color from the linked list is:"); printf("%s\n",item); } void deletion_after_list(linked_list *LS) { char item[20]; node_type *after,*pointer; pointer = LS->head; printf("Enter the name of color after which we want to delete the color:\n"); scanf("%s",&item); after = pointer->next; while(pointer!=NULL) { if(after == NULL) { printf("The item after which the deletion is performed, is the last item in the linked list, this operation is not possible!!!\n"); break; } if(strcmp(pointer->color,item) == 0) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 81

printf("Deleted color from the linked list is:"); printf("%s\n",after->color); pointer->next = after->next; break; } else { pointer = after; after = after->next; } } } void deletion_end_list(linked_list *LS) { node_type *pointer,*previous; pointer = LS->head; if(pointer->next == NULL) { printf("Deleted color from the linked list is:"); printf("%s\n",pointer->color); LS->head = NULL; } else { while(pointer!=NULL) { previous = pointer; pointer = pointer->next; if(pointer->next == NULL) { printf("Deleted color from the linked list is:"); printf("%s\n",previous->next->color); break; } } previous->next = NULL; } free(pointer); } void display(node_type *p) { while(p!=NULL) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

82 Data Strcutures

printf("%s\n",p->color); p = p->next; } printf("\n"); } (v) Output of the Program This program performs the deletion operations on a specified positions in a linked list of colors! !!Please create the list of colors!! Enter the color name(Please enter END for stop): RED Enter the color name(Please enter END for stop): BLUE Enter the color name(Please enter END for stop): PINK Enter the color name(Please enter END for stop): GREEN Enter the color name(Please enter END for stop): END Entered colors in a linked list are: RED BLUE PINK GREEN ###############Menu############# 1: Delete an element in the beginning of the linked list. 2: Delete an element after the specified element of a linked list. 3: Delete an element at the end of the linked list. 4: End. Please enter choice 1 Deleted color from the linked list is:RED Entered colors in a linked list are: BLUE PINK GREEN Please enter choice 3 Deleted color from the linked list is:GREEN Entered colors in a linked list are: BLUE PINK

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 83

Please enter choice 2 Enter the name of color after which we want to delete the color: BLUE Deleted color from the linked list is: PINK Entered colors in a linked list are: BLUE Please enter choice 1 Deleted color from the linked list is: BLUE Linked list is empty!!! Please enter choice 4 End.

2.4 CIRCULAR LINKED LIST
A circular linked list is a linear collection of data elements called nodes. Each node contains two parts of information. The first part contains the information of the element called INFO and second part contains the address of next node in the list called LINK. The list requires a pointer variable START, which points to the first node in the list and the last node points back to the first node instead of containing the NULL pointer called circular linked list. Figure 2.3 shows a circular linked list :
START RED BLUE PINK

Fig. 2.3 Circular Linked List

When there is only one node in the circular linked list the address part LINK of the node points back to itself.

2.5 JOSPHUS PROBLEM
Josphus problem is an application of circular linked list. It consists of a group of soldiers surrounded by an overwhelming enemy force. There is a single horse available for escape. To find out which soldier is to escape, they form a circle and a number n and the name is picked from a hat. They begin to count clockwise around the circle, beginning with the soldier, whose name is picked. One solider is deleted from the circle on which count reaches n. The count start again with next soldier, removing soldiers each time the count reaches n. The last remaining soldier is the one to take the horse. Our problem is to find out the order in which the soldiers will escape. The number n and the list of names of the soldiers are the input

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

84 Data Structures

to the problem. The names are according to the clockwise ordering of the circle beginning with the soldier from whom the count is to start. The output of the program writes the names in the order in which they are removing and the name of the soldier who escapes. Implementation of the Josephus Problem : The following program josephus.c shows the implementation of josephus problem : /*josephus.c*/ #include<stdio.h> #include<stdlib.h> #include<conio.h> typedef struct jose_tag { char name[30]; struct jose_tag *next; }josephus; josephus *getnode(); void addnode(josephus **, josephus *); void createnode(josephus *); void countnode(josephus **, int *); void main() { josephus *phg=NULL; int n; createnode(phg); printf("Input number to be moved:\n"); scanf("%d",&n); countnode(phg,&n); } josephus *getnode(void) { josephus *temp; temp =(josephus*)malloc(sizeof(josephus)); printf("Input name\n"); scanf("%s",temp->name); temp->next = NULL; return(temp); } void addnode(josephus **pphl, josephus *temp) { josephus *travel=NULL; if(*pphl == NULL) { *pphl = temp;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 85

(*pphl)->next = NULL; } else { travel = *pphl; while(travel->next!=(*pphl)) { temp->next = *pphl; travel->next = temp; travel = travel->next; } } } void createnode(josephus *pphl) { josephus *ltp; char ch = 'Y'; ltp = NULL; do { ltp = getnode(); addnode(&pphl,ltp); printf("Want to add more names \n"); fflush(stdin); scanf("%c",&ch); }while(ch=='y'); } void countnode(josephus **pphl,int *lpn) { josephus *travel,*temp; int ctr; temp=travel=NULL; travel=*pphl; if(*lpn==1) { while(travel->next!=*pphl) travel=travel->next; printf("Name left is%s\n",travel->name); return; } else { while(travel->next!=*pphl)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

86 Data Structures

{ for(ctr=1;ctr<=(*lpn);ctr++) travel=travel->next; temp=travel->next; travel->next=travel->next->next; travel=travel->next; free(temp); } printf("Name left is:%s\n",travel->name); } }

2.6 DOUBLY LINKED LIST
A doubly linked list or two-way list is a linear collection of data elements called nodes. Each node is divided into three parts : (i) First part contains the information of the element called INFO. (ii) A pointer field next, which contains the location of the next node in the list. (iii) A pointer field back, which contains the location of the preceding node in the list. The list also requires list pointer variable, called head, which points to the first node in the list. For example, fig. 2.4 shows a double linked list structure of color names with 3 nodes, each node contains one item field(color name) and two address fields. One for predecessor node called left link and the other for successor node called right link of a node. The left link of the left most node and the right link of the right most node are NULL denoted by X in the pointer field. head
RED BLUE PINK X

Fig. 2.4 Linked List

2.6.1 Declaration : The head points to the first node in the double linked list. The following is the declaration of the double linked list : /*node declaration */ typedef struct node_tag{ char item[30]; struct node_tag *next; struct node_tag *back; }node_type; /* Double linked list declaration */ typedef struct dl_tag{ node_type *Head; }dl_list;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 87

2.7 POLYNOMIAL MANIPULATION USING LINKED LIST
Polynomial manipulation is an application of linked list. The main advantage of linked list for polynomial representation is that it can accommodate a number of polynomials of growing sizes so that their combined size does not exceed the total memory available. Let us take an example of polynomial : P(x) = 5x4 + 3x3 + 4x2 + 6x + 7 The polynomial contains two things, coefficient and exponent and a formal variable x. We can drop x as being simply a placeholder. Therefore, we can say that each term of the polynomial consists of a coefficient and an exponent. We will assume that the terms of the polynomial always store in descending order of exponents.The computer implementation requires implementing polynomial as a list of terms of coefficient and exponent. Each of these terms will constitute a structure, which contains 3 fields of fixed size. One field represent the coefficient, second represent exponent and third is a pointer to the next term. The structure of a node in order to represent a term can be: coeff exp
Fig. 2.5

next

It is evident that number of nodes required to represent a polynomial is the same as the number of terms in the polynomial. One additional node called head is also considered for pointing the first node of the linked list. The following is the linked list representation of the polynomial P(x) : P(x) = 5x4 + 3x3 - 4x2 + 6x + 7 head 5 4 3 3
Fig. 2.6

-4 2

6 1

7 0

(i) Declaration : The following is the structure declaration for the polynomial manipulation : typedef struct poly_tag { int coeff; int expo; struct poly_tag *next; }poly; Where coeff stores the coefficient of the term, expo stores the exponent of the term and next stores the pointer to the next node representing next term.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

88 Data Structures

(ii) Polynomial Addition : In this topic, we will discuss the basic operation addition of two polynomials. Let us take two polynomials X and Y. In order to add polynomial X and Y to get a resultant polynomial Z, we need to read their terms starting from the first node and moving towards the end of the polynomials. If the exponent of the two terms are equal, then we add the coefficient and a new term is created and added to the resulting polynomial. If the exponent of the term in polynomial X is less than the exponent of the term in polynomial Y then Y is copied and is added to the resulting polynomial Z. Similarly, if the exponent of the term in polynomial X is greater than the exponent of the term in polynomial Y then X is copied and is added to the resulting polynomial Z. When we reach the end of one of the polynomials, then any remaining part of the other polynomial is copied to the resulting polynomial. We must take care of zero coefficient terms. These terms are not included in the resulting polynomial. (A) Algorithm : Following is the algorithm for implementing polynomial addition of two polynomials. Let us take two pointers Xptr and Yptr in order to traverse the polynomial X and Y, respectively. (a) Xptr=Xhead, Yptr=Yhead (b) Zhead[coeff]=NULL, Zhead[expo]=NULL, Zhead[next] =NULL (c) Zptr = Zhead (d) [Scan the polynomials starting from the first nodes] Repeat Step (e) to (g) while((Xptr!=NULL) &&(Yptr!=NULL)) (e) [Exponent of the current terms of the two polynomials are equal] If (Xptr[expo] = Yptr[expo]) then Set Zptr[coeff] = Xptr[coeff]+Yptr[coeff] Zptr[expo]=Xptr[expo] Zptr[next] = NULL Xptr = Xptr[next], Yptr = Yptr[next] (f) [Exponent of the current term of the first polynomial is greater than the exponent of current term of the second polynomial] If (Xptr[expo] > Yptr[expo]) then Set Zptr[coeff] = Xptr[coeff] Zptr[expo] = Xptr[expo] Zptr[next] = NULL Xptr = Xptr[next] (g) [Exponent of the current term of the first polynomial is less than the exponent of current term of the second polynomial] If (Xptr[expo] < Yptr[expo]) then Set Zptr[coeff] = Yptr[coeff] Zptr[expo] = Yptr[expo]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 89

Zptr[next] = NULL Yptr = Yptr[next] (h) [Copy remaining terms from the first polynomial] If ((Xptr!=NULL) &&(Yptr==NULL)) then Repeat while(Xptr!=NULL) Set Zptr[coeff] = Xptr[coeff] Zptr[expo] = Xptr[expo] Zptr[next] = NULL Xptr = Xptr[next] (i) [Copy remaining terms from the second polynomial] If ((Xptr==NULL) &&(Yptr!=NULL)) then Repeat while(Yptr!=NULL) Set Zptr[coeff] = Yptr[coeff] ` Zptr[expo] = Yptr[expo] Zptr[next] = NULL Yptr = Yptr[next] (j) End. (B) Equivalent Funciton in C void addpoly(poly *Xptr, poly *Yptr,poly *Zptr) { poly *Zhead; Zptr=Zhead; /*Scan the polynomials starting from the first nodes*/ while((Xptr!=NULL) && (Yptr!=NULL)) { /*Exponent of the current term of the first polynomial is greater than the exponent of current term of the second polynomial */ if(Xptr->expo > Yptr->expo) { Zptr=add_node(Zptr,Xptr->expo,Xptr->coeff); Xptr=Xptr->next; } else /*Exponent of the current term of the first polynomial is less than the exponent of current term of the second polynomial */ if(Xptr->expo < Yptr->expo) { Zptr=add_node(Zptr,Yptr->expo,Yptr->coeff); Yptr = Yptr->next; } else

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

90 Data Structures

/*Exponent of the current terms of the two polynomials are equal*/ { Zptr=add_node(Zptr,Xptr->expo,(Xptr->coeff+ Yptr->coeff)); Xptr=Xptr->next; Yptr=Yptr->next; } } /*Copy remaining terms from the second polynomial*/ if((Xptr==NULL) && (Yptr!= NULL)) { while(Yptr!=NULL) { Zptr=add_node(Zptr,Yptr->expo,Yptr->coeff); Yptr=Yptr->next; } } /*Copy remaining terms from the first polynomial*/ if((Xptr!=NULL) && (Yptr== NULL)) { while(Xptr!=NULL) { Zptr=add_node(Zptr,Xptr->expo,Xptr->coeff); Xptr=Xptr->next; } } Zptr->next=NULL; /* Display the addition of the two polynomial */ display(Zhead->next); } (C) Implementation of the Polynomial Addition Operation : Following program poly_addition.c shows the linked list implementaion of the polynomials addition operation : /*poly_addition.c*/ #include<stdio.h> #include<malloc.h> typedef struct poly_tag{ int coeff; int expo; struct poly_tag *next; }poly; poly start; void createpoly(poly *);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 91

poly *add_node(poly *,int,int); void addpoly(poly *,poly *,poly *); void display(poly *); void main() { poly *Xptr = NULL,*Yptr=NULL,*Zptr=NULL; printf("!!!This Program performs the addition of two polynominals!!!\n"); printf("Enter the first polynomial\n"); createpoly(Xptr); Xptr = &start; Xptr = Xptr->next; printf("\nEnter the second polynomial\n"); createpoly(Yptr); Yptr = &start; Yptr = Yptr->next; printf("\nThe sum of the two polynoimals is :"); addpoly(Xptr,Yptr,Zptr); } void createpoly(poly *temp) { char ch; start.next = NULL; temp = &start; do { temp->next = (poly *)malloc(sizeof(poly)); temp = temp->next; printf("Enter the exponent of x is descending order:"); scanf("%d",&temp->expo); printf("Enter its coefficient:"); scanf("%d",&temp->coeff); temp->next = NULL; printf("Do you want to add some other term:"); fflush(stdin); scanf("%c",&ch); }while(ch=='y'); printf("The polynomial is:\n"); temp = &start; temp =temp->next; display(temp); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

92 Data Structures

void addpoly(poly *Xptr, poly *Yptr,poly *Zptr) { poly *Zhead; Zptr=Zhead; while((Xptr!=NULL) && (Yptr!=NULL)) { if(Xptr->expo > Yptr->expo) { Zptr=add_node(Zptr,Xptr->expo,Xptr->coeff); Xptr=Xptr->next; } else if(Xptr->expo < Yptr->expo) { Zptr=add_node(Zptr,Yptr->expo,Yptr->coeff); Yptr = Yptr->next; } else { Zptr=add_node(Zptr,Xptr->expo,(Xptr->coeff+ Yptr->coeff)); Xptr=Xptr->next; Yptr=Yptr->next; } } if((Xptr==NULL) && (Yptr!= NULL)) { while(Yptr!=NULL) { Zptr=add_node(Zptr,Yptr->expo,Yptr->coeff); Yptr=Yptr->next; } } if((Xptr!=NULL) && (Yptr== NULL)) { while(Xptr!=NULL) { Zptr=add_node(Zptr,Xptr->expo,Xptr->coeff); Xptr=Xptr->next; } } Zptr->next=NULL; display(Zhead->next); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 93

poly *add_node(poly *list, int deg, int coef) { list->next = (poly *)malloc(sizeof(poly)); list =list->next; list->expo = deg; list->coeff = coef; return(list); } void display(poly *ptr) { while(ptr!=NULL) { if (ptr->coeff == 0) ptr = ptr->next; else { printf("%dx ^%d",ptr->coeff,ptr->expo); ptr = ptr->next; if(ptr!=NULL) printf("+"); } } printf("\n"); } (D) Output of the Program !!!This Program performs the addition of two polynominals!!! !Enter the first polynomial! Enter the exponent of x is descending order:7 Enter its coefficient:3 Do you want to add some other term:y Enter the exponent of x is descending order:4 Enter its coefficient:4 Do you want to add some other term:y Enter the exponent of x is descending order:3 Enter its coefficient:5 Do you want to add some other term:n The polynomial is: 3x ^7+4x ^4+5x ^3 !Enter the second polynomial! Enter the exponent of x is descending order:7 Enter its coefficient:-3 Do you want to add some other term:y Enter the exponent of x is descending order:5

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

94 Data Structures

Enter its coefficient:5 Do you want to add some other term:y Enter the exponent of x is descending order:3 Enter its coefficient:2 Do you want to add some other term:n The polynomial is: -3x ^7+5x ^5+2x ^3 The sum of the two polynoimals is :5x ^5+4x ^4+7x ^3

2.8 REPRESENTATION OF SPARSE MATRICES
A sparse matrix is a two dimensional array having the value of majority elements as null. Storing of null elements of a sparse matrix is nothing but wastage of memory.So, we should develop a method such that only non zero elements may be stored. Linked list is one of the solution to store the non-zero elements. The following is the structure for represting sparse matrix : i INFO COLUMNLINK
Fig. 2.7 Structure of a Node to Represent Sparse Matrix

j

ROWLINK

Fig. 2.7 shows the structure of a node to represent sparse matrix. Fields i and j store row and column numbers for a matrix element, respectively. INFO field stores the matrix element at the i’th row and j’th column. The ROWLINK and COLUMNLINK points to the next node in the same row and same column, respectively. All the nodes of the row/column are circular linked with each other and each row/column contains a header node. Therefore, for a sprase matrix of nxm, we have to maintain n headers for rows and m headers for columns. One header node can also be used for keeping the starting address of the sparse matrix. Let us take a sparse matrix of 6x4 containing 6 elements, as shown in fig 2.8. 1 2 3 4 0 0 3 0 1 0 5 0 0 2 0 0 0 2 3 1 0 0 4 4 0 0 0 0 5 0 0 7 0 6
Fig. 2.8 A Sparse Matrix of 6x4 Containing 6 Elements

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 95

Fig. 2.9 shows the representation of a sparse matrix of 6x4. There are 6 headers namely ROH1,ROH2,…,ROH6 for 6 rows and 4 headers namely COH1,COH2,…,COH4 for 4 columns. HEAD is an additional header used to reference the sparse matrix. HEAD COH1 0 1 COH2 0 2 COH3 0 3 COH4 0 4

6 ROH1 1 ROH2 2 ROH3 3 ROH4 4 ROH5 5

4

0

1 3

3

0

2 5

2

0

3 2

4

0

4 1

1

4 4

4

0

ROH6 6 0

6 7

3

Fig. 2.9 Linked List Representation of a Sparse Matrix of 6x4

2.9 STACKS
The easiest kind of list to use is called a stack and is defined formally as a list in which all insertions and deletions are made at one end called the top of the stack. Only the top element is moved when it is added or deleted. When we add an element to a stack, we say that we push it on to the stack and when we remove an element, we say that we pop it from the stack. Stack is sometimes also called Last In First Out(LIFO) list.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

96 Data Structures

Let us take an example, we may think of a stack of plates on the counter in busy cafeteria or a stack of books in bookstall etc., as shown in figure 2.10. Whenever, we wish to pick up a tray or a book, we pick it up off the top of the stack. When, we wish to put them back, we place them on the top of the stack. The plate or the book most recently put on the stack is the first one taken off. This is the most important property of the stack in which last element pushed into the stack is taken out first called as LIFO.

Fig. 2.10 Stack of Plates at the Counter in a Cafeteria

Stack is very useful in any ordered and sequential processing of functions. It plays an important role in recursion. It saves memory. The concept of stack is frequently used in valuing raw materials, spares and components in the manufacturing process. It is recognised accounting concept. 2.9.1 Array Implementation of Stack : The simplest way to represent a stack is by using a one-dimensional array. In C language a stack can be defined as a structure containing two objects: an array to hold the elements of the stack and an integer to indicate the position of the current stack top within the array. Type definition for a sequentially allocated stack is: # DEFINE STACKSIZE 100 typedef struct stack_tag { int TOP; /*indicate the position of the current top stack within array */ int element[STACKSIZE]; /* an array to hold stack elements */ }stack; Let us take an example for showing the array representation of a stack. Figure 2.11 shows such representation. Since TOP=5, the stack has five elements GWALIOR, BHOPAL, INDORE, JABALPUR, UJJAIN and since STACKSIZE=9, there is room for 4 more elements in the stack. But there is one potential hazard that we need to declare the size of an array before we start the operation.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 97

9 STACKSIZE

5 TOP

9 8 7 6 5 4 3 2 1

UJJAIN JABALPUR INDORE BHOPAL GWALIOR

Fig. 2.11 Stack

2.9.1.1 Various Operations of Stack : The following are the operations, which are performed on the stack through array implementation : (i) Initialise a stack(initialise operation). (ii) Check whether a stack is empty(empty operation). (iii) Check whether a stack is full(full operation). (iv) Push an element (push operation) onto a stack (if not full). (v) Pop an element (pop operation) from a stack (if not empty). (i) Initialisation Operation : This operation initialise the stack passed as parameter. (A) Algorithm : Following are the steps for initialisation operation of stack : (a) Initialise the stack using TOP=0 (b) End. (B) Equivalent C Function /* Function to initialise a stack Input : stack Output : the stack is initialised */ void initialise(stack *S) { S->TOP = 0; } (ii) Empty Operation : To check whether the stack is empty, we just need to check the value of TOP. If it is less than or equal to zero, then we say that stack is empty. (A) Algorithm : Following are the steps for empty operation of a stack : (a) If (TOP<=0) then print the stack is empty (b) End. (B) Equivalent C Function /* Function to check for empty stack Input : stack Output : 1(true) if stack is empty 2(false) if stack is not empty */

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

98 Data Structures

int empty(stack S) { if (S.TOP <= 0) { printf(“Stack is empty\n”); return(1); } } (iii) Full Operation : To check whether the stack is full, we just need to check the value of TOP. If it is greater than or equal to STACKSIZE, then we say that stack is full. (A) Algorithm : Following are the steps for full operation of a stack : (a) If (TOP>=STACKSIZE) then print the stack is full (b) End. (B) Equivalent C Function /* Function to check for full stack Input : stack Output : 1(true) if stack is full 0(false) if stack is not full */ int full(stack S) { if (S.TOP >= STACKSIZE) { printf(“Stack is full\n”); return(1); } } (iv) Push Operation : The push operation pushes an element on the top of the stack. (A) Algorithm : Following are the steps for push operation of a stack : (a) [Check overflow condition] If (TOP>=STACKSIZE) then print the stack is full and exit (b) [Insert element in new top position] S[TOP] = item (c) [Increment the pointer value TOP by one] TOP = TOP + 1 (d) End. (B) Equivalent C Function /* Function to push an item on the stack Input : stack and item Effect : item is pushed onto stack */ void push(stack *S, int item) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 99

if (S->TOP >= STACKSIZE) { printf(“Stack is full\n”); exit(0); } else { S->element[S->TOP] = item; S->TOP = S->TOP + 1; } } (v) Pop Operation : The pop operation deletes or removes the topmost item from the stack. (A) Algorithm : Following are the steps for pop operation of a stack : (a) [Check whether the stack is empty] If (TOP<=0) then print the stack is empty and return (b) [Decrement TOP by one] TOP = TOP – 1 (c) [Assign TOP element to item] item = S[TOP] (d) [Return top most item from stack] return(item) (e) End. (B) Equivalent C Function /* Function to pop an item on the stack Input : stack and item Output : return top most element of stack */ int pop(stack *S) { if (S->TOP <= 0) { printf(“Stack is empty\n”); return(1); } else { S->TOP = S->TOP - 1; item = S->element[S->TOP]; } return (item); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

100 Data Structures

2.9.1.2 Implementing of Stack Operations Using Array : The following program stack_array_operation.c shows the array implementation of all the operations of stack in numbers : /* Implementation of stack operations using array */ /* stack_array_operation.c */ #include<stdio.h> #define STACKSIZE 100 typedef struct stack_tag { int TOP; int element[STACKSIZE]; }stack; void initialise(stack *); void display(stack *); void push(stack *, int); void pop(stack *, int); void main() { int item,choice; stack S; initialise(&S); printf("This program performs the stack push and pop operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Push"); printf("\n2: Pop "); printf("\n3: End "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: if (S.TOP >= STACKSIZE) { printf("Stack is full\n"); continue; } else { printf("Enter number to be pushed\n"); scanf("%d",&item);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 101

push(&S,item); S.TOP--; printf("Entered elements in a stack are:-"); display(&S); S.TOP++; continue; } case 2: pop(&S,item); if (S.TOP<=0) { printf("There is no element in a stack.\n"); continue; } else { S.TOP--; printf("Entered elements in a stack are:-"); display(&S); S.TOP++; continue; } case 3: printf("End."); return; } }while(choice!=3); } void initialise(stack *S) { S->TOP=0; } void push(stack *S, int item) { if (S->TOP >= STACKSIZE) { printf("Stack is full\n"); exit(0); } else { S->element[S->TOP] = item; S->TOP = S->TOP +1; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

102 Data Structures

void pop(stack *S, int item) { if (S->TOP <=0) { printf("Stack is empty\n"); } else { S->TOP = S->TOP -1; item = S->element[S->TOP]; printf("Number is poped: %d\n",item); } } void display(stack *S) { int x; x=S->TOP; for(x;x>=0;--x) { printf("%d\t",S->element[x]); } printf("\n"); } Output of the Program This program performs the stack push and pop operations on numbers! ###############Menu############# 1: Push 2: Pop 3: End Please enter choice 1 Enter number to be pushed 12 Entered elements in a stack are:-12 Please enter choice 1 Enter number to be pushed 23 Entered elements in a stack are:-23 12 Please enter choice 1 Enter number to be pushed 34

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 103

Entered elements in a stack are:-34 23 12 Please enter choice 2 Number is poped: 34 Entered elements in a stack are:-23 12 Please enter choice 2 Number is poped: 23 Entered elements in a stack are:-12 Please enter choice 2 Number is poped: 12 There is no element in a stack. Please enter choice 2 Stack is empty There is no element in a stack. Please enter choice 3 End 2.9.2 Linked Implementation of Stack : Pointer representation of a stack runs parallel to array representation. Stack is highly simplified version of linked lists. Although this method of allocating storage is adequate for many applications, there are many other applications where the sequential allocation method is inefficient and, therefore, unacceptable. For such applications we store a stack element in a structure with a pointer to the next lower element on the stack. In C language the linked stack can be defined as follows : /*node declaration */ typedef struct node_tag { int info; struct node_tag *next; }node_type; /*stack declaration */ typedef struct stack_tag { node_type *TOP; }stack; 2.9.2.1 Various Operations of Linked Stack : The following are the operations, which are performed on the stack through linked implementation :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

104 Data Structures

(i) Initialise a stack(initialise operation). (ii) Function to make a node(create_node) of item. (iii) Push an element (push_node operation) onto a linked stack (if not full). (iv) Pop an element (pop_node operation) from a linked stack (if not empty). (i) Initialisation Operation : This operation initialise the linked stack passed as parameter. (A) Algorithm : Following are steps of initialising the linked stack : (a) Initialise the stack using TOP=NULL (b) End. (B) Equivalent C Function /* Function to initialise a linked stack Input : stack Output : the linked stack is initialised */ void initialise(stack *S) { S->TOP = NULL; } (ii) Create Node Operation : This operation creates a new node for the given item. (A) Algorithm : Following are the steps for creating a node in a linked stack : (a) [Get memory to node] p = (node_type*)malloc(sizeof(node_type)) (b) [Check whether memory is available or not] If(p==NULL) memory is not available overflow and exit (c) [Prepare node using] p->info = x p->next = NULL (d) [Return node pointer containing item] return p (e) End. (B) Equivalent C Function /* Function to prepare a node from info Input : item x Output : The node pointer containing item */ node_type *create_node( int x) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); if(p==NULL) { printf(“Memory overflow\n”);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 105

return(0); } else { p->info = x; p->next = NULL; } return p; } (iii) Push Operation : The push operation pushes an element on linked stack. (A) Algorithm : Following are the steps for push operation on linked stack : (a) [Prepare node using function make_node of item x] p = make_node(x) (b) [Check whether stack is empty or not] If(S->TOP==NULL) then push the node on the top of the stack using S->TOP = p (c) [Otherwise push node onto top of the stack using] p->next = S->TOP S->TOP = p (d) End. (B) Equivalent C Function /* Function to push an item on linked stack Input : item x, stack Output : push node on linked stack */ void push_node( int x, stack *S) { node_type *p; p = create_node(x); if(S->TOP==NULL) S->TOP=p; else { p->next = S->TOP; S->TOP = p; } } (iv) Pop Operation : This operation pop up an item from linked stack. (A) Algorithm : Following are the steps for pop operation on linked stack : (a) [Check whether the stack is empty] If (S->TOP== NULL) then print the stack is empty and exit

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

106 Data Structures

(b) [Create temporary pointer using] p = S->TOP (c) [Advance stack pointer by node] S->TOP = p->next (d) [Get item info using] x = p->info (e) [Release memory] free(p) (f) [Return item info from function] return x (g) End. (B) Equivalent C Function /* Function to pop an item from linked stack Input : stack Output : return item*/ int pop_node(stack *S) { int x; node_type *p; if(S->TOP == NULL) { printf(“stack underflow\n”); return(0); } else { p= S->TOP; S->TOP = p->next; x = p->info; free(p); } return x; } 2.9.2.2 Implemention of Linked Stack Operations : The following program stack_linked_operation.c shows the linked implementation of all the operations of stack in numbers : /* stack_linked_operation.c */ #include<stdio.h> #include<stdlib.h> /*node declaration */ typedef struct node_tag { int info; struct node_tag *next; }node_type;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 107

/*stack declaration */ typedef struct stack_tag { node_type *TOP; }stack; void initialise(stack * ); void display(node_type *); node_type *make_node(int x); void push_node(stack * , int); void pop_node(stack * , int); void main() { int choice,item; stack *S; initialise(S); printf("This program performs the linked stack push and pop operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Push"); printf("\n2: Pop "); printf("\n3: End "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter number to be pushed\n"); scanf("%d",&item); printf("Entered elements in a stack are:-"); push_node(S,item); display(S->TOP); continue; case 2: pop_node(S,item); if (S->TOP==NULL) { printf("There is no element in a stack.\n"); continue; } else {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

108 Data Structures

printf("Entered elements in a stack are:-"); display(S->TOP); continue; } case 3: printf("End"); return; } }while(choice!=3); } void initialise(stack *S) { S->TOP=NULL; } node_type *make_node(int x) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); if(p==NULL) { printf("Memory overflow\n"); return(0); } else { p->info = x; p->next = NULL; } return p; } void push_node(stack *S, int x) { node_type *p; p = make_node(x); if (S->TOP==NULL) { S->TOP = p; exit(0); } else { p->next = S->TOP; S->TOP = p; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 109

void pop_node(stack *S, int x) { node_type *p; if(S->TOP == NULL) { printf("stack underflow\n"); exit(0); } else { p= S->TOP; S->TOP = p->next; x = p->info; printf("Number is poped: %d\n",x); free(p); } } void display(node_type *p) { while(p!=NULL) { printf("%d\t",p->info); p = p->next; } printf("\n"); } Output of the Program This program performs the linked stack push and pop operations on numbers ###############Menu############# 1: Push 2: Pop 3: End Please enter choice 1 Enter number to be pushed 12 Entered elements in a stack are:-12 Please enter choice 1 Enter number to be pushed 23 Entered elements in a stack are:-23 12

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

110 Data Structures

Please enter choice 1 Enter number to be pushed 34 Entered elements in a stack are:-34 Please enter choice 2 Number is poped: 34 Entered elements in a stack are:-23 Please enter choice 2 Number is poped: 23 Entered elements in a stack are:-12 Please enter choice 2 Number is poped: 12 There is no element in a stack. Please enter choice 2 stack underflow There is no element in a stack. Please enter choice 3 End

23

12

12

2.10 MULTIPLE STACK
Sometimes a program requires two or more stacks containing the same type of elements. If we can store stacks in separate arrays then it might be possible that one stack is full while others have unused space. Let us take two stacks and try to put into one array. Solution to this problem is put to all the space in single array and assume that one stack grows from one end of the array while second stack starts at the other end and grows in opposite direction towards the first stack. In this case there will be no overflow until all the space is actually used. 2.10.1 Declaration of Double Stack : Declaration of double stack structure includes two pointers TOPA and TOPB and an array element. # DEFINE STACKSIZE 100 typedef struct stack_tag { int TOPA; /*indicate the position of the current top in stackA within array */ int TOPA; /*indicate the position of the current top in stackB within array */ int element[STACKSIZE]; /* an array to hold stack elements */ } stack;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 111

2.10.2 Various Operations of Double Stack : The following are the operations, which are performed on the double stack through array implementation : (i) Initialise a double stack(initialise operation). (ii) Push an element (pushA operation) onto a stackA. (iii) Pop an element (popA operation) from a stackA. (iv) Push an element (pushB operation) onto a stackB. (v) Pop an element (popB operation) from a stackB. (i) Initialisation Operation : This operation initialises the stackA and stackB passed as parameter. (A) Algorithm : Following are the steps for initialisation operation of double stack : (a) Initialise the stackA using TOPA=0 (b) Initialise stackB using TOPB = STACKSIZE-1 (c) End. (B) Equivalent C Function /* Function to initialise stackA, stackB Input : stack Output : the stacks are initialised */ void initialise(stack *S) { S->TOP = 0; S->TOPB = STACKSIZE-1; } (ii) PushA Operation : The pushA operation pushes an element on the top of the stackA. (A) Algorithm : Following are the steps for push operation on stackA : (a) [Check overflow condition] If (TOPA>TOPB) then print the stack is full and exit (b) [Insert element in new top position] S[TOPA] = item (c) [Increment the pointer value TOPA by one] TOPA = TOPA + 1 (d) End. (B) Equivalent C Function /* Function to push an item on the stackA Input : stack and item Effect : item is pushed onto stackA */ void pushA(stack *S, int item) { if (S->TOPA > S->TOPB) { printf(“StackA is full\n”);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

112 Data Structures

exit(0); } else { S->element[S->TOPA] = item; S->TOPA = S->TOPA + 1; } } (iii) PopA Operation : The popA operation deletes or removes the topmost item from the stackA. (A) Algorithm : Following are the steps for pop operation on stackA : (a) [Check whether the stack is empty] If (TOPA==0) then print the stack is empty and return (b) [Decrement TOPA by one] TOPA = TOPA – 1 (c) [Assign TOPA element to item] item = S[TOPA] (d) [Return top most item from stack] return(item) (e) End. (B) Equivalent C Function /* Function to pop an item on the stackA Input : stack and item Output : return top most element of stackA */ int popA(stack *S) { int item; if (S->TOPA == 0) { printf(“StackA is empty\n”); return(1); } else { S->TOPA = S->TOPA - 1; item = S->element[S->TOPA]; } return (item); } (iv) PushB Operation : The pushB operation pushes an element on the top of the stackB. (A) Algorithm : Following are the steps for push operation on stackB : (a) [Check overflow condition]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 113

If (TOPA>TOPB) then print the stack is full and exit (b) [Insert element in new top position] S[TOPB] = item (c) [Decrement the pointer value TOPB by one] TOPB = TOPB - 1 (d) End. (B) Equivalent C Function /* Function to push an item on the stackB Input : stack and item Effect : item is pushed onto stackB */ void pushB(stack *S, int item) { if (S->TOPA > S->TOPB) { printf(“StackB is full\n”); exit(0); } else { S->element[S->TOPB] = item; S->TOPB = S->TOPB - 1; } } (v) PopB Operation : The popB operation deletes or removes the topmost item from the stackB. (A) Algorithm : Following are the steps for pop operation on stackB : (a) [Check whether the stack is empty] If (TOPB == STACKSIZE-1) then print the stackB is empty and return (b) [Increment TOPB by one] TOPB = TOPB + 1 (c) [Assign TOPB element to item[ item = S[TOPB] (d) [Return top most item from stack] return(item) (e) End. (B) Equivalent C Function /* Function to pop an item on the stackB Input : stack and item Output : return top most element of stackB */ int popB(stack *S) { int item;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

114 Data Structures

if (S->TOPB ==(STACKSIZE-1)) { printf("StackB is empty\n"); return(1); } else { S->TOPB = S->TOPB +1; item = S->element[S->TOPB]; } return (item); } 2.10.3 Implemention of Double Stack Operations Using Array : The following program stack_double_operation.c shows the array implementation of all the operations of double stack in numbers : /* Implementation of double stack operations using array */ /*stack_double_operation.c*/ #include<stdio.h> #define STACKSIZE 100 typedef struct stack_tag { int TOPA; int TOPB; int element[STACKSIZE]; }stack; void initialise(stack *); void displayA(stack *); void displayB(stack *); void pushA(stack *, int); void popA(stack *, int); void pushB(stack *, int); void popB(stack *, int); void main() { int item,choice; stack S; initialise(&S); printf("This program performs the stack push and pop operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Push into stack A"); printf("\n2: Pop from stack A"); printf("\n3: Push into stack B");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 115

printf("\n4: Pop from stack B"); printf("\n5: End "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: if (S.TOPA > S.TOPB) { printf("StackA is full!\n"); continue; } else { printf("Enter number to be pushed in stackA:\n"); scanf("%d",&item); pushA(&S,item); S.TOPA--; printf("Entered elements in a stackA are:-"); displayA(&S); S.TOPA++; continue; } case 2: popA(&S,item); if (S.TOPA<0) { printf("There is no element in stackA.\n"); continue; } else { S.TOPA--; printf("Entered elements in a stackA are:-"); displayA(&S); S.TOPA++; continue; } case 3: if (S.TOPA > S.TOPB)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

116 Data Structures

{ printf("StackB is full!\n"); continue; } else { printf("Enter number to be pushed in stackB:\n"); scanf("%d",&item); pushB(&S,item); S.TOPB++; printf("Entered elements in a stackB are:-"); displayB(&S); S.TOPB--; continue; } case 4: popB(&S,item); if (S.TOPB==STACKSIZE) { printf("There is no element in stackB.\n"); continue; } else { S.TOPB++; printf("Entered elements in a stackB are:-"); displayB(&S); S.TOPB--; continue; } case 5: printf("end"); return; } }while(choice!=5); } void initialise(stack *S) { S->TOPA=0; S->TOPB=STACKSIZE-1; } void pushA(stack *S, int item) { if (S->TOPA > S->TOPB)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 117

{ printf("StackA is full!\n"); } else { S->element[S->TOPA] = item; S->TOPA = S->TOPA +1; } } void popA(stack *S, int item) { if (S->TOPA ==0) { printf("StackA is empty!\n"); } else { S->TOPA = S->TOPA -1; item = S->element[S->TOPA]; printf("Number is poped from StackA: %d\n",item); } } void pushB(stack *S, int item) { if (S->TOPA > S->TOPB) { printf("StackB is full!\n"); } else { S->element[S->TOPB] = item; S->TOPB = S->TOPB -1; } } void popB(stack *S, int item) { if (S->TOPB ==(STACKSIZE-1)) { printf("StackB is empty!\n"); } else { S->TOPB = S->TOPB +1;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

118 Data Structures

item = S->element[S->TOPB]; printf("Number is poped from stackB: %d\n",item); } } void displayA(stack *S) { int x; x=S->TOPA; for(x;x>=0;--x) { printf("%d\t",S->element[x]); } printf("\n"); } void displayB(stack *S) { int x; x=S->TOPB; for(x;x<STACKSIZE;x++) { printf("%d\t",S->element[x]); } printf("\n"); } Output of the Program This program performs the stack push and pop operations on numbers using stackA and stackB! ###############Menu############# 1: Push into stack A 2: Pop from stack A 3: Push into stack B 4: Pop from stack B 5: End. Please enter choice 1 Enter number to be pushed in stackA: 12 Entered elements in a stackA are:-12 Please enter choice 1 Enter number to be pushed in stackA: 23 Entered elements in a stackA are:-23 12

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 119

Please enter choice 2 Number is poped from StackA: 23 Entered elements in a stackA are:-12 Please enter choice 3 Enter number to be pushed in stackB: 34 Entered elements in a stackB are:-34 Please enter choice 3 Enter number to be pushed in stackB: 56 Entered elements in a stackB are:-56 34 Please enter choice 4 Number is poped from stackB: 56 Entered elements in a stackB are:-34 Please enter choice 4 Number is poped from stackB: 34 There is no element in a stackB. Please enter choice 4 StackB is empty! Please enter choice 5 End.

2.11 VARIOUS POLISH NOTATIONS
An arithmetic expression involving constants and operations can be represented in three types of notations. These are : (i) Infix Notation : In this type of notation, the binary operator is placed between the operands. Examples A + B C - D E * F G/H (ii) Prefix Notation : In this type of notation, the binary operator is placed before the operands. It is also called Polish notation because it is introduced by the Polish mathematician Lukasiewicx. Examples +AB -CD *EF /GH (iii) Postfix Notation : In this type of notation, the binary operator is placed after the operands. It is also called reverse Polish notation.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

120 Data Structures

Examples AB+ CDEF* GH/ 2.11.1 Conversion from One Notation to Another : Let Q is an arithmetic expression that contains two types of variable: operators and operands. It also contains parenthesis to change the priority of operation. The following is the order of precedence of operators for evaluation of arithmetic expressions : Table 2.1
Operators Priority

Exponention(^ or ↑), -(unary minus) 6 *, /, % 5 +, -(binary) 4 ==, != 3 <,<=,>,>= 2 &&, || 1 = 0 If two same priority operators are encountered in the expression then operators are evaluated from left to right, except in case of priority 6 operators. In this case the operators are evaluated from right to left. (i) Conversion from Infix to Postfix Notation : Following are the examples, which convert the infix notation arithmetic expression(let Q) to equivalent postfix notation. Example 1: Q = (A-B) / ((C+D)*E) Solution Q = (A-B) / ((C+D)*E) = (AB-)/((CD+)*E) = (AB-)/(CD+E*) = AB-CD+E*/ Example 2: Q = ((A+B)/C)^((D-E)*F) Solution Q = ((A+B)/C)^((D-E)*F) = ((AB+)/C)^((DE-)*F) = (AB+C/)^(DE-F*) = AB+C/DE-F*^ Example 3: Q = (A+B^C)/(D-E)+F Solution Q = (A+B^C)/(D-E)+F = (A+BC^)/(DE-)+F = (ABC^+)/(DE-)+F = (ABC^+DE-/)+F = ABC^+DE-/F+

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 121

Example 4: Q = A*(B+C)/D-E*(F+G/H) Solution Q = A*(B+C)/D-E*(F+G/H) = A*(BC+)/D-E*(F+(GH/) = ABC+*/D-E*(FGH/+) = ABC+*D/-EFGH/+* = ABC+*D/EFGH/+*Example 5: Q = A*B-C*D/E Solution Q = A*B-C*D/E = AB*-C*D/E = AB*-CD*/E = AB*-CD*E/ = AB*CD*E/(ii) Conversion from Infix to Prefix Notation : Following are the examples, which convert the infix notation arithmetic expression(let Q) to equivalent prefix notation. Example 1: Q = (A+B^C^D)*(E+F/G) Solution Q = (A+B^C^D)*(E+F/G) = (A+^BC^D)*(E+/FG) = (A+^^BCD)*(+E/FG) =(+A^^BCD)*(+E/FG) = *+A^^BCD+E/FG Example 2 : Q = A*B*(C+D) Solution Q = A*B*(C+D) = A*B*(+CD) = *AB*(+CD) = **AB+CD Example 3: Q = A-(B+C)*(D+E) Solution Q = A-(B+C)*(D+E) = A-(+BC)*(+DE) = A-*+BC+DE = -A*+BC+DE Example 4: Q = (A-B)*(D/E) Solution Q = (A-B)*(D/E) = (-AB)*(/DE) = *-AB/DE

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

122 Data Structures

Example 5: Q = A+B/C*D^(E+F) Solution Q = A+B/C*D^(E+F) = A+B/C*D^(+EF) = A+B/C*^D+EF = A+/BC*^D+EF = A+*/BC^D+EF = +A*/BC^D+EF (iii) Conversion from Prefix to Infix Notation : Following are the examples, which convert the prefix notation arithmetic expression(let Q) to equivalent infix notation. Example 1: Q = *+ABC Solution Q = *+ABC = +AB*C = A+B*C Example 2: Q = +A*/BC^D+EF Solution Q = +A*/BC^D+EF = +A*/BCD^+EF = +A/BC*D^+EF = +AB/C*D^+EF = A+B/C*D^+EF = A+B/C*D^(E+F)

2.12 CONVERSION OF INFIX TO POSTFIX NOTATION USING STACK
We can convert infix notation expression into postfix notation expression using stack data structure. The following is the algorithm, which uses stack(S) to convert the expression into postfix notation expression P. Algorithm : Following are the steps for conversion of infix to postfix notation expression using stack : (i) Read the entire expression(Q) in array name ‘element’ and add “.” to the end of the expression Q. (ii) Initialise the stack to be empty. (iii) Read the infix expression(using array ‘element’) from left to right and repeat step (iv) to (vii) for each element of Q until the end of the array ‘element’ is encountered indicated by the “.” : (iv) If a left parenthesis “(“ is encountered, add it onto S. (v) If an operand is encountered, append it to P. (vi) If an operator is encountered then : (a) Repeatedly pop from S and add it to P,each operator on top of the stack, which has the same or higher precedence than the operator encountered.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 123

(b) Push it onto the stack(S). (vii) If a right parenthesis “)” is encountered then : (a) Repeatedly pop from S and add it to P, each operator on top of the stack until a left parenthesis is encountered. (b) Remove the left parenthesis “(“. (viii) Exit. Let us take an example for explaining the algorithm. Consider the following arithmetic infix expression Q : Q = (A + (B - C)/(D * E)) We follow above algorithm to transform Q into equivalent postfix expression P. First we put the expression Q in an array name ‘element’ and put ‘.’ to indicate the end of the expression. Now scan all the items of the array one by one and take appropriate decision based on the algorithm. Table 2.2 shows the operation of the conversion process : Table 2.2
Symbol Scanned from Q using Array ‘element’ STACK(S) Status #(empty) Postfix Expression(P)

#( ( A #( A A #(+ + A #(+( ( AB #(+( B AB #(+(ABC #(+(C ABC#(+ ) ABC#(+/ / ABC#(+/( ( ABC-D #(+/( D ABC-D #(+/(* * ABC-DE #(+/(* E ABC-DE* #(+/ ) ABC-DE*/+ # ) 2.12.1 Implementation of Algorithm: The program stack_infix_postfix.c shows the array implementation, which converts the infix notation arithmetic expression into postfix notation expression using stack : /* This program will convert the infix notation arithmetic expression into postfix notation expression using stack */ /* stack_infix_postfix.c */ #include<stdio.h> #include<ctype.h> #include<string.h> #include<stdlib.h>

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

124 Data Structures

#define STACKSIZE 100 typedef char item_type; typedef struct s_tag { int TOP; item_type element[STACKSIZE]; }stack; void initialise (stack *S); void push(stack *, char x[]); void pop(stack *); void infix_to_postfix(); int m,len; char q[80],c; void main() { printf("This program converts the infix expression into postfix expression using stack!\n"); printf("Please enter expression: To quit enter fullstop(.)\n"); while((c=getc(stdin))!='\n') { q[m]=c; m++; } len=m; infix_to_postfix(); } void initialise(stack *S) { S->TOP = 0 ; } void push(stack *S, char q[]) { if( S->TOP >= STACKSIZE) { printf("\nStack is full\n"); } else { S->element[S->TOP] = q[m]; S->TOP = S->TOP+1; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 125

void pop(stack *S) { if (S->TOP < 0) { printf("Stack is empty\n"); } else { if(S->TOP >=0) { S->TOP = S->TOP-1; if(S->element[S->TOP]!='(') printf("%c",S->element[S->TOP]); } } } void infix_to_postfix() { stack S; initialise(&S); m=0; while(m<len) { switch(q[m]) { case '+' : case '-' : while(S.element[S.TOP-1]=='-'|| S.element[S.TOP-1]=='+' || S.element[S.TOP-1]=='*' || S.element[S.TOP-1]=='/' || S.element[S.TOP-1] =='^' && S.element[S.TOP-1] !='(') pop(&S); push(&S,q); ++m; break; case '/' : case '*' : while(S.element[S.TOP-1]=='*' || S.element[S.TOP-1]=='/' || S.element[S.TOP-1]=='^' && S.element[S.TOP-1] !='(')

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

126 Data Structures

pop(&S); push(&S,q); ++m; break; case '^' : push(&S,q); ++m; break; case '(' : push(&S,q); ++m; break; case ')' : while(S.element[S.TOP-1]!='(') pop(&S); pop(&S); ++m; break; case '.' : while (S.TOP >= 0) pop(&S); exit(0); if(isalpha(q[m])) { printf("%c",q[m]); ++m; break; } else { printf("error"); exit(0); }

default :

} } } Output of the Program This program converts the infix expression into postfix expression using stack! Please enter expression: To quit enter fullstop(.) (a+b)/(c^(d*e)-f)*g. ab+cde*^f-/g*

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 127

Please enter expression: To quit enter fullstop(.) (a-b) / ((c+d)*e). ab-cd+e*/

2.13 EVALUATION OF POSTFIX AND EXPRESSION
We can also use stack to evaluate expressions of postfix notation. To do this, add a ‘.’ to indicate the end of the expression. Now scan the expression P from left to right. When an operand is encountered, it is pushed onto the stack, when an operator is encountered, it is applied to the first two operands that are obtained by popping the stack and die result is pushed onto the stack. Following is the algorithm, which uses stack(S) to evaluate the postfix expression P : Algorithm : Following are the steps for evaluation of postfix expression : (i) Read and store the entire expression in an array say element. (ii) Examine each item of expression one by one from left to right. (iii) If item is an operand push it onto stack S. and go to step(ii). (iv) If item is an operator pop two operands from the stack and perform the arithmetic operation on them. Push result on the stack and go to step(ii). (v) If item is an ‘.’ pop the result from the stack and print the evaluated result. (vi) End. Let us take an example for explaining the algorithm. Consider the following arithmetic postfix expression P : P=853+9*+4+ We follow above algorithm to evaluate postfix expression P. The equivalent infix expression is : I = 8 + (5 + 3) * 9 + 4 The evaluation procedure of the expression is given in the table 2.3 : Table 2.3
Symbol Scanned Stack

8 5 3 + 9 * + 4 +

8 85 853 88 889 8 72 80 80 4 84

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

128 Data Structures

End of the string is encountered therefore stack is popped out and the result is 84. 2.13.1 Implementation of the Algorithm : The following program stack_postfix_eval.c shows the array implementation, which evaluate the arithmetic postfix expression P, using stack : /* This program will evaluate the arithmetic postfix expression P, using stack */ /*stack_postfix_eval.c*/ #include<stdio.h> #include<ctype.h> #include<math.h> #include<stdlib.h> #define STACKSIZE 100 typedef int item_type; typedef struct s_tag { int TOP; item_type element[STACKSIZE]; }stack; void initialise(stack *S); void push(stack *, int); int pop(stack *); void postfix_eval(); int m,len=0; int q[STACKSIZE]; void main() { char *str; printf("This program evaluates the postfix expression using stack!\n"); printf("Please enter expression(each character is separeted by space character,"); printf("To quit enter fullstop'.')\n"); gets(str); while(*str) { if((isdigit(*str)) && (!isspace(*(++str)--))) { q[m]=atoi(str); str= str +2; m++; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 129

else { if (isdigit(*(str))) { q[m]=atoi(str); str= str +1; m++; } } q[m]=(*str); ++str; m++; if (*str == '.') { q[m]=(*str); m++; break; } } len = m; postfix_eval(); } void initialise(stack *S) { S->TOP = 0 ; } void push(stack *S, int item) { if( S->TOP >= STACKSIZE) { printf("\nStack is full\n"); } else { S->element[S->TOP] = item; S->TOP = S->TOP+1; } } int pop(stack *S) { int item; if (S->TOP < 0) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

130 Data Structures

printf("Stack is empty\n"); } else { if(S->TOP >=0) { S->TOP = S->TOP-1; item = S->element[S->TOP]; } } return item; } void postfix_eval() { int p1,p2,temp; stack S; initialise(&S); m=0; while(m<len) { switch(q[m]) { case ' ' : m++; break; case '+' : p1=pop(&S); p2=pop(&S); temp = p2 + p1; push(&S,temp); m++; break; case '-' : p1=pop(&S); p2=pop(&S); temp = p2 – p1; push(&S,temp); m++; break; case '*' : p1=pop(&S); p2=pop(&S); temp =p2 * p1;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 131

push(&S,temp); m++; break; case '/' : p1=pop(&S); p2=pop(&S); temp =p2 / p1; push(&S,temp); m++; break; case '%' : p1=pop(&S); p2=pop(&S); temp =p2 % p1; push(&S,temp); m++; break; case '^' : p1=pop(&S); p2=pop(&S); temp = pow(p2, p1); push(&S,temp); m++; break; case '.' : temp = pop(&S); printf("The evaluated expression is :"); printf("%d\n",temp); exit(0); default : temp = q[m]; push(&S,temp); ++m; break; } } } Output of the Program This program evaluates the postfix expression using stack!(each character is separated by space character, To quit enter fullstop'.') Please enter expression : 4 6 10 + -. result of the postfix

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

132 Data Structures

The evaluated result of the postfix expression is :12 This program evaluates the postfix expression using stack!(each character is separated by space character, To quit enter fullstop'.') Please enter expression : 5 3 + 4 * 2 5 - ^ 4 +. The evaluated result of the postfix expression is : 32772

2.14 RECURSION
Recursion is a process by which the function calls itself repeatedly until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. The following are the conditions, which must be satisfied to solve a problem recursively : (a) The problem must be written in a recursive form. (b) The problem statement must include a stopping condition. 2.14.1 Types of Recursion : This section descirbes some of the ways in which recursive functions are characterised. (i) Direct Recursion : A function that call to itself is called a direct recursion. For example, the function : int temp( int y) { if(y == 0) return y; return temp(y-1); } includes a call to itself. (ii) Indirect Recursion : A function is called indirect function, if it contains a call to another function which ultimately calls the caller function,i.e., they call each other. For example, the function : int temp(int y) { if( y == 0) return y; return check(y); } int check(int z) { return temp(z –1); } is an example of indirectly recursive. (iii) Tail Recursion : A recusrive function is called a tail recursion, if there are no pending operations to be performed on return from a recursive call. For example, function factorial :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 133

int factorial(int m) { if (m == 0) return 1; return m*factorial(m-1); } is an example of non-tail recursive function. In this function, there is a pending operation multiplication, to be performed on return from each recursive call. Whenever, their is a pending operation, the function is non-tail recursive. The following function factorial written in a tail recursive way : int factorial(int m, int temp) { if (m == 0) return temp; return factorial(m-1, m*temp); } int fact(m) { return factorial(m,1); } (iv) Tree Recursion : A function is called a tree recursion, when the pending operation does involve another recursive call to the function. For example, the function fibonacci is an example of tree recursion : int fib(int m) { if (n==0) return 0; if (n==1) return 1; return fib(n-1) + fib(n-2); } (v) Linear Function : A recursive function is called a linearly recursive function, when no pending operation involves another recursive call to the function. Many examples of recursion techniques may be found, the technique is useful both for the definition of mathematical functions and for the definition of data structures. Naturally, if a data structure may be defined recursively, it may be processed by a recursive function. Many problems can be solved recursively. Games of all types from simple ones like the Towers of Hanoi problem to complex ones like chess. In games, the recursive solutions are particularly convenient because, it solved the problem by a series of recursive calls, we want to find out how we got to the solution.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

134 Data Structures

Some of the functions that may be defined recursively are : (i) Factorial (ii) Fibonacci (iii) Euclid's GCD (greatest common denominator) (iv) Towers of Hanoi (i) Factorial : One of the simplest example of a recursive definition is calculating the factorial of a number. Following is the definition : factorial( n ) = 1 n * factorial( n-1 ) if ( n = 0 ) if (n > 0)

A natural way to calculates factorial is to write a recursive function, which matches the above definition. (A) Algorithm : The following is the algorithm for calculating the factorial of a number : (a) If n=0 then Set factorial :=1 and return (b) Call factorial(factorial,n-1) (c) Set factorial := n* factorial (d) Return (B) Equivalent C Function int factorial( int n ) { if ( n == 0 ) return 1; else return n* factorial(n-1); } Note how this function calls itself to evaluate the next term. Eventually, it will reach the termination condition and exit. However, before it reaches the termination condition, it will have pushed n stack frames onto the program's run-time stack. The termination condition is obviously extremely important when dealing with recursive functions. If it is omitted, then the function will continue to call itself until the program runs out of stack space - usually with moderately unpleasant results. (C) Implementation of Factorial Function : The following program recursion_fact.c shows implementation of the factorial function : /*recursion_fact.c*/ #include<stdio.h> int factorial(int); void main() { int n, fact; printf(“This program calculates the factorial of a number!!!!\n”);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 135

printf(“Please enter the number of which we want to calculate the factorial:\n”); scanf(“%d”,&n); fact =factorial(n); printf(“Factorial of %d = %d”,n,fact); } int factorial( int n ) { if ( n == 0 ) return 1; else return n* factorial(n-1); } (D) Output Of the Above Program This program calculates the factorial of a number!!!! Please enter the number of which we want to calculate the factorial: 5 Factorial of 5 is = 120 This program calculates the factorial of a number!!!! Please enter the number of which we want to calculate the factorial: 10 Factorial of 10 is = 3628800 (ii) Fibonacci : Another commonly used example of a recursive function is the generation of fibonacci series. Following is the definition : 0 1 fib( n-1 ) + fib( n-2 ) if ( n = 0 ) if ( n = 1 ) if (n >= 2)

fib( n ) =

The following is the fibonacci series, which is generated with the help of the above fibonacci defination : 0,1,1,2,3,5,8,13,21,34,55 … From the above series it is clear that each succeeding term is the sum of the two preceding terms. (A) Algorithm : The following is the algorithm for generating the fibonacci series : (a) If n=0 then Set fib :=0 and return (b) If n=1 then Set fib:=1 and return (c) Call fib(fib,n-2) (d) Call fib(fib,n-1) (e) Set fib = fib(n-1) + fib(n-2) (B) Equivalent C Function int fib( int n ) { if (n == 0)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

136 Data Structures

return 0; else if(n==1) return 1; else return fib(n-1) + fib(n-2); } (C) Implementation of Fibonacci Function : The following program recursion_fib.c shows implementation of the fibonacci function : /*recursion_fib.c*/ #include<stdio.h> int fib(int); void main() { int i=0, n, fibonacci; printf("This program generates the series of fibonacci number!!!!\n"); printf("Please enter the number for fibonacci series, we want to generate:\n"); scanf("%d",&n); printf("Fibonacci series is as follows :"); while(i<n) { fibonacci =fib(i); printf("%d\t", fibonacci); ++i; } } int fib( int n ) { if (n == 0) return 0; else if(n==1) return 1; else return fib(n-1) + fib(n-2); } (D) Output Of the Above Program This program generates the series of fibonacci number!!!! Please enter the number for fibonacci series, we want to generate: 7 Fibonacci series is as follows :0 1 1 2 3 5 8

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 137

(iii) Greatest Common Denominator (Euclid's GCD) : A more complex recursive example is to find the greatest common denominator of two positive integers with the help of EUCLID’s GCD algorithm. Following is the definition : GCD(m,n) If (n < m) m If (n >= m) && (n mod m = 0) GCD(m,n mod m) Otherwise (A) Algorithm : The following is the algorithm for finding the GCD of two positive integers : (a) If (n>=0) and (n%m)==0 then return m (b) Otherwsie call GCD(m,(n%m)) (B) Equivalent C Function int GCD( int n, int m ) { if ((n >= m) && ((n%m)==0)) return m; else GCD(m,(n%m)); } (C) Implementation of GCD Function : The following program recursion_gcd.c shows implementation of the GCD function : /*recursion_gcd.c*/ #include<stdio.h> int GCD(int,int); void main() { int n,m, gcd; printf("This program finds the greatest common denominator of two positive integers!!!!\n"); printf("Please enter the first integer :”); scanf("%d",&n); printf("Please enter the second integer :”); scanf("%d",&m); gcd = GCD(n,m); printf("Greatest common denominator of: %d and %d is = %d",n,m,gcd); } int GCD( int n, int m ) { if ((n >= m) && ((n%m)==0)) return m; else GCD(m,(n%m)); } GCD(n,m) =

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

138 Data Structures

(D) Output Of the Above Program This program finds the greatest common denominator of two positive integers!!!! Please enter the first integer :120 Please enter the second integer :9 Greatest common denominator of: 120 and 9 is = 3 (iv) Tower of Hanoi : The Tower of Hanoi is a recursive example, that is based on three pegs and a set of disks of graduated sizes. Let us suppose that three pegs labelled A,B,C are given and on peg A there are finite number of disks n in increasing size order, i.e., biggest one at the bottom and smallest one at the top. The problem is to move disk from peg A to peg C using peg B whenever it is required. The following are the rules for moving the disk : (a) Only one disk may be moved at a time. (b) The top disk on any peg may be moved to any other peg. (c) A larger disk can not be placed on a smaller one at no time. The solution to the problem is very simple, when there are only one or two disks to move : For n=1 : A → C(only one move) For n=2: A → B, A → C, B → C (three move) The problem is complicated when the disks are more then two. Let us take the Tower of Hanoi problem with three disks. The figure 2.12 shows the pictorial representation of the solution to the problem :

Fig. 2.12 Tower of Hanoi Problem with n=3

The following is the move, which is performed for the solution of Tower of Hanoi problem with n=3 disks : Move disk from peg A to peg C Move disk from peg A to peg B

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 139

Move disk from peg C to peg B Move disk from peg A to peg C Move disk from peg B to peg A Move disk from peg B to peg C Move disk from peg A to peg C For n=3 : A → C, A → B, C → B, A → C, B → A, B → C, A → C Now, we use the technique of recursion to develop a general solution for all values of n. We observe that the solution to the Tower of Hanoi problem with n>1 disks may be reduced to the following subproblems : (a) Move the top(n-1) disks from A to B. (b) Move the top disk from A to C. (c) Move the top n-1 disks from B to C. (A) Algorithm : The following is the algorithm for the solution of the Tower of Hanoi problem : (a) If (n=1) then move the disk from peg A to peg C and exit (b) [Move n-1 disks from peg A to peg B] Call Tower_of_Hanoi(n-1,A,C,B) (c) Move the top disk from peg A to peg C (d) [Move n-1 disks from peg B to peg C] Call Tower_of_Hanoi(n-1,B,A,C) (e) End. (B) Equivalent C Function void Tower_of_Hanoi(int n, char A, char B, char C) { if(n<=0) printf(“Incorrect input\n”); else if(n ==1) printf("Move disk from peg %c to peg %c\n",A,C); else { Tower_of_Hanoi(n-1,A,C,B); Tower_of_Hanoi(1,A,B,C); Tower_of_Hanoi(n-1,B,A,C); } } (C) Implementation of Tower of Hanoi Function : The following program recursion_TOF.c shows implementation of the Tower of Hanoi function : /*recursion_TOF.c*/ #include<stdio.h> void Tower_of_Hanoi(int,char,char,char);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

140 Data Structures

void main() { int n; printf("This program shows the solution of the Tower of Hanoi problem for n disks!!!!\n"); printf("Please enter the number of disk:”); scanf("%d",&n); printf(“Tower of Hanoi problem for %d disk”,n); Tower_of_Hanoi(n,’A’,’B’,’C’); } void Tower_of_Hanoi(int n, char A, char B, char C) { if(n<=0) printf(“Incorrect input\n”); else if(n ==1) printf("Move disk from peg %c to peg %c\n",A,C); else { Tower_of_Hanoi(n-1,A,C,B); Tower_of_Hanoi(1,A,B,C); Tower_of_Hanoi(n-1,B,A,C); } } (D) Output of the Above Program This program shows the solution of the Tower of Hanoi problem for n disks!!!! Please enter the number of disk:1 Tower of Hanoi problem for 1 disk. Move disk from peg A to peg C This program shows the solution of the Tower of Hanoi problem for n disks!!!! Please enter the number of disk:3 Tower of Hanoi problem for 3 disk. Move disk from peg A to peg C Move disk from peg A to peg B Move disk from peg C to peg B Move disk from peg A to peg C Move disk from peg B to peg A Move disk from peg B to peg C Move disk from peg A to peg C

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 141

2.14.2 Advantages of Recursion : The following are some advantages of recursion : (i) It is more concise, compact and transparent. (ii) In certain cases it may be easier to write and understand. (iii) In data structure like linked lists, queues, stacks, quicksort etc., recursion is handier. (iv) In certain problems like Tower of Hanoi, recursion may be the only solution. (v) Recursion reduces the programming, as recursion requires less coding. (vi) In case the programmer is able to reduce use of stack, local variables, recursive program is equally efficient as non-recursive programs. (vii) Recursion is a powerful in mathematical definition. Finite recursion statements can define an infinite set of objects. (viii) Recursion is very useful, where function or subroutine is required. (ix) Recursion is eminently useful if the solution to problem is in recursive terms. (x) Recursion is more efficient if the programs using recursion are run on computers with multi processing facilities. 2.14.3 Disadvantages of Recursion : The following are some disadvantages of recursion : (i) It consumes more storage space because the recursion calls, along with automatic variables are stored on the stack. (ii) The computer may run out of memory if the recursive calls are not checked. (iii) It is not more efficient in terms of speed and execution time. (iv) According to some computer professional’s recursion does not offer any concrete advantage over non-recursive functions. (v) If proper precautions are not taken, recursion may result in non-terminating iterations. (vi) Recursion is not advocated when the problem can be solved through iteration. Recursion may be treated as a software tool to be applied carefully and selectively.

2.15 QUEUES
A queue a defined as a waiting line, like: a line of people waiting to purchase the tickets. Where the first person in line is the first person served. In computer, we similarly define a queue to be a list in which all additions to the list are made at one end of the queue and all deletions are made at other end of the queue. The item in the queue ready to be served that is the first item that will be deleted from the queue is called the front of the queue and the last item in the queue, which is most

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

142 Data Structures

recently added, is called rear of the queue. Queue is sometimes also called First In First Out(FIFO) list because the item, which is to be added first is removed first. Fig. 2.13(a) and (b) illustrate queues.

2.16

IMPLEMENTATION OF QUEUE

2.16.1 Physical Implementation of a Queue : In Physical implementation of a queue, we define only one pointer that is front and try to keep it in the first position of array. But, when an item is to be deleted, then each item present in the queue is to be shifted one position forward, so as to keep front pointer in the first position. So, this method is time consuming and costlier to be implemented in computer as whenever an item is to be deleted, each item in the queue will have to be moved one memory location forward. 2.16.2 Linear Implementation of Queue : In the linear queue implementation, we consider two indices(counter) to keep track of both front and rear of the queue without moving any item. To add an item into the queue, we simply increase rear by one and put the item in that position. To remove an item we take from the front and then increase front by one. Type definition for the linear queue is : # DEFINE QUEUESIZE 100 typedef struct q_tag { int front, rear; /* pointer for addition and deletion in a queue */ int element[QUEUESIZE]; /* an array to hold queue elements */ } queue;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 143

Let us take an example for showing the array representation of a queue. Consider a queue, which has the QUEUESIZE of 5. Initially, the queue is empty. It is required to insert the numbers 12,23,34, delete 12 and then insert 45, 56 and 67. Figure 2.14 shows such representation.

Empty Front Rear 12 Insert 12 Front Rear 12 23 Insert 23 Front 12 Rear 23 34 Insert 34 Front 23 Rear 34 Delete 12 Front 23 Rear 34 Insert 45 Front 23 34 Insert 56 Front
Fig. 2.14 Array Representation of Queue

45

Rear 45 56

Rear

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

144 Data Structures

2.16.2.1 Drawback of Linear Queue : When we try to insert number 67 overflow occurs even though the first position in the queue is free. This is the situation in which rear pointer reaches to the end of the queue array while there is empty space in queue before the front pointer. Since, addition can only be done at rear, so that no item can be added even at we have empty space in the queue. This is the drawback of linear queue. 2.16.2.2 Solution of Linear Queue Drawback : The drawback of linear queue can be resolved with the help of shifting of items. We can use any one of the two approaches for shifting items : (i) In first approach, as soon as an item is deleted, shift the entire queue towards the beginning of the queue array. It ensures that the front pointer always remains at the 0’th position in the array. So, if there is any space in a queue will be after the rear pointer and can be used for adding new items. But this approach is much time consuming because it requires a lot of data movement operations after every deletion operation. (ii) In second approach, as soon as rear pointer reaches to the end of the queue and front pointer is not at the 0’th position in the queue, shift the entire queue in such a way that front pointer reaches at 0’th position in queue. In this method, the data movement is less as compared to first method but it still requires data movement operations. 2.16.2.3 Various Operations of Linear Queue : The following are the operations, which are performed on the queue through array implementation : (i) Initialise a queue(initialise operation). (ii) Check whether the queue is empty(empty operation). (iii) Check whether the queue is full(full operation). (iv) Add an element (Insertion operation) at the rear of a queue (if not full). (v) Delete an element (deletion operation) from the front of the queue (if not empty). (i) Initialisation Operation : This operation initialises the queue passed as a parameter. (A) Algorithm : Following are the steps for initialisation of a queue : (a) Initialise the queue using rear=0, front=0 (b) End. (B) Equivalent C Function /* Function to initialise a queue Input : queue Output : the queue is initialised */ void initialise(queue *Q) { Q->front = 0;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 145

Q->rear = 0; } (ii) Empty Operation : To check whether the queue is empty, we just need to check the value of front. If it is less than or equal to zero, then we say that queue is empty. (A) Algorithm : Following are the steps for empty operation of a queue : (a) [Check underflow condition] If (front<=0) then print the queue is empty (b) End. (B) Equivalent C Function /* Function to check for empty queue Input : queue Output : 1(true) if queue is empty 2(false) if queue is not empty */ int empty(queue Q) { if (Q.front <= 0) { printf(“Queue is empty\n”); return(1); } } (iii) Full Operation : To check whether the queue is full, we just need to check the value of rear. If it is greater than or equal to QUEUESIZE, then we say that queue is full. (A) Algorithm : Following are the steps for full operation in a queue : (a) [Check overflow condition] If (rear>=QUEUESIZE) then print the queue is full (b) End. (B) Equivalent C Function /* Function to check for full queue Input : queue Output : 1(true) if queue is full 0(false) if queue is not full */ int full(queue Q) { if (Q.rear >= QUEUESIZE) { printf(“Queue is full\n”); return(1); } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

146 Data Structures

(iv) Insertion Operation : The insertion operation adds an element on the rear of the queue. (A) Algorithm : Following are the steps for insertion operation in a queue : (a) [Check overflow condition] If (rear>=QUEUESIZE) then print overflow and exit (b) [Queue has only one element] If(front =NULL) then Set front :=1, rear :=1 (c) [Otherwise increment the rear pointer by one] rear = rear + 1 (d) [Insert an element in to the rear of the queue] Q[rear] = item (e) End. (B) Equivalent C Function /* Function to add an item to the rear of the queue Input : queue and item Effect : item is added on the rear of the queue */ void insertion(queue *Q, int item) { if (Q->rear >= QUEUESIZE) { printf("Queue is full!\n"); exit(0); } if (Q->front == NULL) { Q->front = 1; Q->rear = 1; } else { Q->rear = Q->rear +1; } Q->element[Q->rear] = item; } (v) Deletion Operation : The deletion operation deletes or removes the item from the front of the queue. (A) Algorithm : Following are the steps for insertion operation in a queue : (a) [Check underflow condition] If (front == NULL) then print underflow and return (b) [Otherwise assign element from the front of the queue to item] Set item := Q[front]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 147

(c) [Check for empty queue] If(front =rear) then Set front := 0, rear :=0 (d) [Otherwise Increment front by one] front := front + 1 (e) [Return item from the front of the queue] return(item) (f) End. (B) Equivalent C Function /* Function to delete an item on the queue Input : queue and item Output : return item from the front of the queue */ int deletion(queue *Q, int item) { if (Q->front == 0) // Queue already empty { printf("Underflow!!!\n"); return(1); } else { item = Q->element[Q->front]; } if (Q->front==Q->rear) //Queue has only one item { Q->front =0; Q->rear = 0; } else { Q->front = Q->front +1; } return item; } 2.16.2.4 Implementation of Linear Queue Operations using Array : The following program queue_operation.c shows the array implementation of all the operations of queue in numbers : /* Implementation of queue operations using array */ /* queue_operation.c */ #include<stdio.h> #include<stdlib.h> #define QUEUESIZE 100 typedef struct q_tag {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

148 Data Structures

int front,rear; int element[QUEUESIZE]; }queue; void initialise(queue *); void display(queue *); void insertion(queue *, int); int deletion(queue *, int); void main() { int x,item,choice; queue Q; initialise(&Q); printf("This program performs the queue addition and deletion operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Insert"); printf("\n2: Deletion "); printf("\n3: End "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: if (Q.rear >= QUEUESIZE) { printf("Queue is full\n"); continue; } else { printf("Enter number to be added\n"); scanf("%d",&item); insertion(&Q,item); printf("Entered elements in a queue are:-"); display(&Q); continue; } case 2: x = deletion(&Q,item); if (Q.front==0) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 149

continue; } else { printf("Entered elements in a queue are:-"); display(&Q); continue; } case 3: printf("End."); return; } }while(choice!=3); } void initialise(queue *Q) { Q->front=0; Q->rear =0; } void insertion(queue *Q, int item) { if (Q->rear >= QUEUESIZE) { printf("Queue is full!\n"); } if (Q->front == NULL) { Q->front = 1; Q->rear = 1; } else { Q->rear = Q->rear +1; } Q->element[Q->rear] = item; } int deletion(queue *Q, int item) { if (Q->front == 0) { printf("Underflow!!!\n"); return(1); } else {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

150 Data Structures

item = Q->element[Q->front]; printf("Number is deleted: %d\n",item); } if (Q->front==Q->rear) { Q->front =0; Q->rear = 0; printf("Now Queue is empty!\n"); printf("There is no element in a queue.\n"); } else { Q->front = Q->front +1; } return item; } void display(queue *Q) { int x; x=Q->front; for(x;x<=Q->rear;x++) { printf("%d\t",Q->element[x]); } printf("\n"); } Output of the Program This program performs the queue addition and deletion operations on numbers! ###############Menu############# 1: Insert 2: Deletion 3: End Please enter choice 1 Enter number to be added 12 Entered elements in a queue are:-12 Please enter choice 1 Enter number to be added 23 Entered elements in a queue are:-12 23

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 151

Please enter choice 1 Enter number to be added 34 Entered elements in a queue are:-12 23 34 Please enter choice 2 Number is deleted: 12 Entered elements in a queue are:-23 34 Please enter choice 2 Number is deleted: 23 Entered elements in a queue are:-34 Please enter choice 2 Number is deleted: 34 Now queue is empty! There is no element in a queue. Please enter choice 2 Underflow!!! Please enter choice 3 End. 2.16.3 Linked Implementation of Queue : If we implement queue as an array across situations when an attempt to insert an element in the queue, it causes overflow. However, queue as an abstract data structure can not be full therefore, it is always possible to insert an element into a queue. Thus, implementing the queue as an array prohibits the growth of the queue beyound the finite number of elements. We must implement the queue in such a way that the queue can grow to the limit of the computer’s memory. One approach is to represent queue as a linked list. In C language, the linked queue can be defined as follows : /*node declaration */ typedef struct node_tag { int info; struct node_tag *next; }node_type; /*queue declaration */ typedef struct q_tag { node_type front,rear; }queue;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

152 Data Structures

2.16.3.1 Various Operations of Linked Queue : The following are the operations, which are performed on the queue through linked implementation : (i) Initialise a queue(initialise operation). (ii) Function to make a node(make_node) of item. (iii) Add an element (add_node operation) onto a linked queue. (iv) Delete an element (delete_node operation) from a linked queue (if not empty). (i) Initialisation Operation : This operation initialises the linked queue passed as parameter. (A) Algorithm : Following are the steps for initialisation of a linked queue : (a) Initialise the queue using front=NULL, rear=NULL (b) End. (B) Equivalent C Function /* Function to initialise a linked queue Input : queue Output : the linked queue is initialised */ void initialise(queue *Q) { Q->front = NULL; Q->rear = NULL } (ii) Create Node Operation : This operation creates a new node for the given item. (A) Algorithm : Following are the steps for creating a node of a linked queue : (a) [Get memory to node] p = (node_type*)malloc(sizeof(node_type)) (b) [Check whether memory is available or not] If(p==NULL) memory is not available overflow and return (c) [Prepare node using] p[info] = x p[next] = NULL (d) [Return node pointer containing item] return p (e) End. (B) Equivalent C Function /* Function to prepare a node from info Input : item x Output : The node pointer containing item */ node_type *make_node( int x) { node_type *p;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 153

p = (node_type*)malloc(sizeof(node_type)); if(p==NULL) printf(“Memory overflow\n”); return(0); else { p->info = x; p->next = NULL; } return p; } (iii) Add Operation : The add operation adds an element on linked queue. (A) Algorithm : Following are the steps for add operation of a linked queue : (a) [Prepare node using function make_node of item x] p = make_node(x) (b) [Check whether queue is empty or not] If(front==NULL) then queue is empty and front and rear pointer assign the node p Set Q[front] := p Q[rear] := p (c) [Insert node in the queue] else Q[rear][next] := p Q[rear] := p; (d) End. (B) Equivalent C Function /* Function to add an item on linked queue Input : item x, queue Output : add node on linked queue */ void add_node(queue *Q, int x) { node_type *p; p = make_node(x); if (Q->front==NULL) { Q->front = p; Q->rear = p; } else { Q->rear->next = p; Q->rear = p; } }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

154 Data Structures

(iv) Delete Operation : This operation deletes an item from linked queue. (A) Algorithm : Following are the steps for deletion operation of a linked queue : (a) [Check underflow condition] If (front== NULL) then print the underflow and return (b) [Create temporary pointer using] p = Q[front] (c) [Advance front pointer by node] Q[front] = p[next] (d) [Check queue has only one element] If(Q[front] == Q[rear]) then Set Q[rear] = NULL (e) [Get item info using] x = p[info] (f) [Release memory] free(p) (g) [Return item from function] return x (h) End. (B) Equivalent C Function /* Function to delete an item from linked queue Input : queue Output : return item*/ int delete_node(queue *Q, int x) { node_type *p; if(Q->front == NULL) { printf("queue underflow\n"); return; } else { p= Q->front; Q->front = p->next; if (Q->front == Q->rear) Q->rear = NULL; x = p->info; free(p); } return x; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 155

2.16.3.2 Implementation of Linked Queue Operations : The following program queue_linked_operation.c shows the linked implementation of all the operations of queue in numbers : /* Implementation of linked queue operations */ /* queue_linked_operation.c */ #include<stdio.h> #include<stdlib.h> /*node declaration */ typedef struct node_tag { int info; struct node_tag *next; }node_type; /*queue declaration */ typedef struct q_tag { node_type *front,*rear; }queue; void initialise(queue * ); void display(node_type *); node_type *make_node(int x); void add_node(queue * , int); void delete_node(queue * , int); void main() { int choice,item; queue *Q; initialise(Q); printf("This program performs the linked queue addition and deletion operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Addition"); printf("\n2: Deletion "); printf("\n3: End. "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter number to be added\n"); scanf("%d",&item);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

156 Data Structures

printf("Entered elements in a linked queue are:-"); add_node(Q,item); display(Q->front); continue; case 2: delete_node(Q,item); if (Q->front==NULL) { printf("There is no element in a linked queue.\n"); continue; } else { printf("Entered elements in a linked queue are:-"); display(Q->front); continue; } case 3: printf("End"); return; } }while(choice!=3); } void initialise(queue *Q) { Q->front=NULL; Q->rear=NULL; } node_type *make_node(int x) { node_type *p; p = (node_type*)malloc(sizeof(node_type)); if(p==NULL) { printf("Memory overflow\n"); return(0); } else { p->info = x; p->next = NULL; } return p; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 157

void add_node(queue *Q, int x) { node_type *p; p = make_node(x); if (Q->front==NULL) { Q->front = p; Q->rear = p; } else { Q->rear->next = p; Q->rear = p; } } void delete_node(queue *Q, int x) { node_type *p; if(Q->front == NULL) { printf("queue underflow\n"); } else { p= Q->front; Q->front = p->next; if (Q->front == Q->rear) Q->rear = NULL; x = p->info; printf("Number is deleted: %d\n",x); free(p); } } void display(node_type *p) { while(p!=NULL) { printf("%d\t",p->info); p = p->next; } printf("\n"); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

158 Data Structures

Output of the Program This program performs the linked queue addition and deletion operations on numbers! ###############Menu############# 1: Addition 2: Deletion 3: End. Please enter choice 1 Enter number to be added 1 Entered elements in a linked queue are:-1 Please enter choice 1 Enter number to be added 2 Entered elements in a linked queue are:-1 2 Please enter choice 1 Enter number to be added 3 Entered elements in a linked queue are:-1 2 3 Please enter choice 2 Number is deleted: 1 Entered elements in a linked queue are:-2 3 Please enter choice 1 Enter number to be added 4 Entered elements in a linked queue are:-2 3 4 Please enter choice 2 Number is deleted: 2 Entered elements in a linked queue are:-3 4 Please enter choice 2 Number is deleted: 3 Entered elements in a linked queue are:-4 Please enter choice 2 Number is deleted: 4 There is no element in a linked queue.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 159

Please enter choice 2 queue underflow There is no element in a linked queue. Please enter choice 3 End.

2.17 CIRCULAR QUEUE
The major defects in the linear implementation of queue are that both the pointers front and rear always increase and never decrease. The problem of course is that when some items are deleted from the queue, as the queue moves down the array the storage space in the beginning of the queue is discarded. This problem of ineffective utilisation of storage space can be overcome by assuming an array, as a circle rather than a straight line, thus when items are deleted or added in the queue front continuously chases the rear round the array. Different parts of queue will remain occupied at different times and queue will not become full until it is a fully occupied. This type of arrangement of items is called circular queue. Fig. 2.15 illustrates a circular queue.

2.17.1 Implementation of Circular Queue : In a circular queue implementation, positions around the circle are numbered from 1 to CQSIZE, where CQSIZE is the total number of items that can be held in the circular queue. To implement the circular array, we use the same numbered positions for the items as in linear array and moving the pointers(front and rear). When a pointer passes CQSIZE, we start over again at 1. This is like doing arithmetic on a circular clock face. Type definition for the circular queue is :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

160 Data Structures

# DEFINE CQSIZE 100 typedef struct q_tag { int front, rear; /* pointer for addition and deletion in a circular queue */ int element[CQSIZE]; /* an array to hold circular queue elements */ }circular_queue; Let us take an example for showing the array representation of a circular queue. Consider a queue, which has the CQSIZE of 5. Initially, the queue is empty. It is required to insert the numbers 12,23,34 and 45 delete 12 and 23 and then insert 56 and 67. Figure 2.16 shows such representation.

Empty Front Rear 12 Insert 12 Front Rear 12 23 Insert 23 Front 12 Rear 23 34 Insert 34 Front 12 23 Rear 34 Insert 45 Front 23 34 Delete 12 Front Rear Rear 45 45

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 161

34 Delete 23 Front 34

45

Rear 45 Insert 56 56

Front 67 34 45 Insert 67 Rear 67 78 Front 34 45 Insert 78 Rear Front

Rear 56

56

Fig. 2.16 Array Representation of Circular Queue

2.17.2 Drawbacks or Boundary Conditions of Circular Queue (i) If there is exactly one item in queue, then front index will equal to rear index.

Rear Front
Fig. 2.17

(ii) When this item is removed from the queue, then front will increase by one. So, empty queue is indicated when rear is exactly one position behind the front index.

Rear
Fig. 2.18

Front

(iii) Now, suppose that queue is nearly full, then rear move well away from the front index all the way around the circle.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

162 Data Structures

Rear
Fig. 2.19

Front

(iv) When the array is full the rear index will be exactly one position before the front index.

Rear
Fig. 2.20

Front

Thus, we see that in case of empty and full queue, rear and front indices are at the same positions. In both cases front is one position ahead of rear. front = rear + 1 2.17.3 Solution of Circular Queue Drawbacks : Following are the solutions to the circular queue problems : (i) We allow only (CQSIZE-1) items to be put in the queue so in case of full queue, rear index is two positions before the front index and in case of empty queue, rear index is one position before the front index. (ii) We may consider an integer variable, which may count the number of occupied position in the queue. 2.17.4 Various Operations of Circular Queue : The following are the operations, which are performed on the circular queue through array implementation : (i) Initialise a queue(initialise operation). (ii) Check whether the circular queue is empty(empty operation). (iii) Check whether the circular queue is full(full operation). (iv) Add an element (Insertion operation) at the rear of a circular queue (if not full). (v) Delete an element (deletion operation) from the front of the circular queue (if not empty). (i) Initialisation Operation : This operation initialises the circular queue passed as parameter. (A) Algorithm : Following are the steps for initialision operation in circular queue : (a) Initialise the circular queue using rear=0, front=0 (b) End. (B) Equivalent C Function /* Function to initialise a circular queue Input : circular queue

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 163

Output : the circular queue is initialised */ void initialise(circular_queue *CQ) { CQ->front = 0; CQ->rear = 0; } (ii) Empty Operation : To check whether the circular queue is empty, we just need to check the value of front. If it is equal to zero, then we say that circular queue is empty. (A) Algorithm : Following are the steps for empty operation in a circular queue : (a) [Check circular queue is empty or not] If (front==0) then print the circular queue is empty (b) End. (B) Equivalent C Function /* Function to check for empty circular queue Input : circular queue Output : 1(true) if circular queue is empty 2(false) if circular queue is not empty */ int empty(circular_queue CQ) { if (CQ.front == 0) { printf(“Circular queue is empty\n”); return(1); } } (iii) Full Operation : To check whether the circular queue is full, we need to check the value of rear and front. (A) Algorithm : Following are the steps for full operation in a circular queue : (a) [Check overflow condition] If (((rear == (CQSIZE-1)) && (front ==1 )) || (front == (rear + 1))) then print the circular queue is full (b) End. (B) Equivalent C Function /* Function to check for full circular queue Input : circular queue Output : 1(true) if circular queue is full 0(false) if circular queue is not full */ int full(circular_queue CQ) { if (((CQ.rear == (CQSIZE-1)) && (CQ.front ==1 ))|| (CQ.front == (CQ.rear + 1)))

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

164 Data Structures

{ printf("Circular queue is full!\n"); return(1); } } (iv) Insertion Operation : The insertion operation adds an element on the rear of the circular queue. (A) Algorithm : Following are the steps for insertion operation in a circular queue : (a) [Check overflow condition] If ((front ==1 && rear==CQSIZE-1) || (front = rear+1)) then print overflow and return (b) [Circular queue has no element] else if(front =NULL) then Set front :=1, rear :=1 CQ[rear]:=item (c) [Check, if the rear at the end of the circular queue] else if (rear = CQSIZE-1) then Set rear :=1 CQ[rear]:=item (d) [Increment the rear pointer by one and insert an element in to the rear of the circular queue] else rear = rear + 1 CQ[rear] = item (e) End. (B) Equivalent C Function /* Function to add an item to the rear of the circular queue Input : circular queue and item Effect : item is added on the rear of the circular queue */ void insertion(circular_queue *CQ, int item) { if (((CQ->rear == (CQSIZE-1)) && (CQ->front ==1 )) || (CQ->front == (CQ->rear + 1))) { printf("Circular queue is full!\n"); return; } else { if (CQ->front == NULL) { CQ->front = 1;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 165

CQ->rear = 1; CQ->element[CQ->rear] = item; } else if(CQ->rear == CQSIZE-1) { CQ->rear = 1; CQ->element[CQ->rear] = item; } else { CQ->rear = CQ->rear +1; CQ->element[CQ->rear] = item; } } } (v) Deletion Operation : The deletion operation deletes or removes the item from the front of the circular queue. (A) Algorithm : Following are the steps for deletion operation in a circular queue : (a) [Check underflow condition] If (front == NULL) then print underflow and return (b) [Otherwise assign element from the front of the queue to item] Set item := CQ[front] (c) [Check for empty queue] If(front =rear) then Set front := 0, rear :=0 (d) [Check the front pointer position] else if (front = CQSIZE-1) then Set front :=1 (e) [Otherwise Increment front by one] else front := front + 1 (f) [Return item from the front of the queue] return(item) (g) End. (B) Equivalent C Function /* Function to delete an item on the circular queue Input : circular queue and item Output : return item from the front of the circular queue */ void deletion(circular_queue *CQ, int item) { if (CQ->front == 0) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

166 Data Structures

printf("Underflow!!!\n"); return; } item = CQ->element[CQ->front]; CQ->element[CQ->front] = NULL; if (CQ->front==CQ->rear) { CQ->front =0; CQ->rear = 0; } else if (CQ->front == (CQSIZE-1)) CQ->front =1; else CQ->front = CQ->front +1; } 2.17.5 Implemention of Circular Queue Operations using Array : The following program queue_circular_operation.c shows the array implementation of all the operations of circular queue in numbers : /* Implementation of circular queue operations using array */ /* queue_circular_operation.c */ #include<stdio.h> #include<stdlib.h> #define CQSIZE 100 typedef struct cq_tag { int front,rear; int element[CQSIZE]; }circular_queue; void initialise(circular_queue *); void display(circular_queue *); void insertion(circular_queue *, int); void deletion(circular_queue *, int); void main() { int item,choice; circular_queue CQ; initialise(&CQ); printf("This program performs the circular queue addition and deletion operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Insert"); printf("\n2: Deletion ");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 167

printf("\n3: End. "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: insertion(&CQ,item); printf("Entered elements in a circular queue are:-"); display(&CQ); continue; case 2: deletion(&CQ,item); if (CQ.front==0) continue; else { printf("Entered elements in a circular queue are:-"); display(&CQ); continue; } case 3: printf("End."); return; } }while(choice!=3); } void initialise(circular_queue *CQ) { CQ->front=0; CQ->rear =0; } void insertion(circular_queue *CQ, int item) { if (((CQ->rear == (CQSIZE-1)) && (CQ->front ==1 )) || (CQ->front == (CQ->rear + 1))) { printf("Circular queue is full!\n"); return; } else { printf("Enter number to be added\n"); scanf("%d",&item);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

168 Data Structures

if (CQ->front == NULL) { CQ->front = 1; CQ->rear = 1; CQ->element[CQ->rear] = item; } else if(CQ->rear == CQSIZE-1) { CQ->rear = 1; CQ->element[CQ->rear] = item; } else { CQ->rear = CQ->rear +1; CQ->element[CQ->rear] = item; } } } void deletion(circular_queue *CQ, int item) { if (CQ->front == 0) { printf("Underflow!!!\n"); return; } item = CQ->element[CQ->front]; CQ->element[CQ->front] = NULL; printf("Number is deleted: %d\n",item); if (CQ->front==CQ->rear) { CQ->front =0; CQ->rear = 0; printf("Now Circular queue is empty!\n"); printf("There is no element in a circular queue.\n"); } else if (CQ->front == (CQSIZE-1)) CQ->front =1; else CQ->front = CQ->front +1; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 169

void display(circular_queue *CQ) { int x; if ((CQ->rear > 1)&&(CQ->front == (CQ->rear+1))) { x = 1; for(x;x<CQSIZE;x++) { printf("%d\t",CQ->element[x]); } printf("\n"); } else if(CQ->front == (CQ->rear+1)) { x = CQ->rear; for(x;x<=CQSIZE;x++) { printf("%d\t",CQ->element[x]); } printf("\n"); } else if(CQ->front > (CQ->rear +1)) { x = 1; for(x;x<=CQ->rear;x++) { printf("%d\t",CQ->element[x]); } x = CQ->front; for(x;x<CQSIZE;x++) { printf("%d\t",CQ->element[x]); } printf("\n"); } else { x=CQ->front; for(x;x<=CQ->rear;x++) { printf("%d\t",CQ->element[x]);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

170 Data Structures

} printf("\n"); } } Output of the Program This program performs the circular queue addition and deletion operations on numbers! ###############Menu############# 1: Insert 2: Deletion 3: End Please enter choice 1 Enter number to be added 1 Entered elements in a circular queue are:-1 Please enter choice 1 Enter number to be added 2 Entered elements in a circular queue are:-1 2 Please enter choice 1 Enter number to be added 3 Entered elements in a circular queue are:-1 2 3 Please enter choice 1 Enter number to be added 4 Entered elements in a circular queue are:-1 2 3 4 Please enter choice 1 Enter number to be added 5 Entered elements in a circular queue are:-1 2 3 4 5 Please enter choice 1 Circular queue is full! Entered elements in a circular queue are:-1 2 3 4 5 Please enter choice 2 Number is deleted: 1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 171

Entered elements in a circular queue are:-2 Please enter choice 2 Number is deleted: 2 Entered elements in a circular queue are:-3 Please enter choice 1 Enter number to be added 6 Entered elements in a circular queue are:-6 Please enter choice 1 Enter number to be added 7 Entered elements in a circular queue are:-6 Please enter choice 2 Number is deleted: 3 Entered elements in a circular queue are:-6 Please enter choice 1 Enter number to be added 8 Entered elements in a circular queue are:-6 Please enter choice 2 Number is deleted: 4 Entered elements in a circular queue are:-6 Please enter choice 1 Enter number to be added 9 Entered elements in a circular queue are:-6 Please enter choice 3 End.

3

4

5

4

5

3

4

5

7

3

4

5

7

4

5

7

8

4

5

7

8

5

7

8

9

5

2.18 DOUBLE ENDED QUEUE OR DEQUE
It is the linear list in which addition and deletion are made at both the ends i.e., both front and rear. It is also known as deque. Fig. 2.17 represents a deque.
Deletion Insertion Insertion Deletion

Front
Fig. 2.21 Deque

Rear

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

172 Data Structures

There are two forms of deque : (i) Input Restricted Deque : In this type of deque, the addition is performed at rear and deletion is performed from both rear and front. Fig. 2.22 shows such representation.
Deletion Insertion Deletion

Front
Fig. 2.22 Input Restricted Deque

Rear

(ii) Output Restricted Deque : In this type of deque, the addition is performed at front and rear while deletion is performed only from front. Fig. 2.23 shows such representation.
Deletion Insertion Insertion

Front
Fig. 2.23 Output Restricted Deque

Rear

2.18.1 Implementation of Deque : Implementation of deque is similar to the implementation of linear queue. We consider two indices(counter) to keep track of both front and rear of the deque without moving any item. Type definition for the deque is : # DEFINE DQSIZE 100 typedef struct dq_tag { int front, rear; /* pointer for addition and deletion in a deque */ int element[DQSIZE]; /*an array to hold deque elements */ } deque; 2.18.2 Various Operations of Deque : The following are the operations, which are performed on the deque through array implementation : (i) Initialise a deque(initialise operation). (ii) Add an element at rear of the deque (add_at_rear operation). (iii) Delete an element from the front of the deque similar to linear queue (delete_from_front operation). (iv) Add an element at the front of the deque similar to linear queue (add_at_front operation). (v) Delete an element from rear of the deque (delete_from_rear operation). (i) Initialisation Operation : This operation initialises the deque passed as parameter.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 173

(A) Algorithm : Following are the steps for initialising a deque : (a) Initialise the deque using rear=0, front=0 (b) End. (B) Equivalent C Function /* Function to initialise a deque Input : deque Output : the deque is initialised */ void initialise(deque *DQ) { DQ->front = 0; DQ->rear = 0; } (ii) Add at Rear Operation : This operation adds an element at the rear of the deque. (A) Algorithm : Following are the steps for add operation at rear of a deque : (a) [Check overflow condition] if (rear>=DQSIZE) then print overflow and return (b) [Check deque is empty or not] If(rear ==0) && (front ==0) then DQ[rear] = item & rear = rear +1 (c) [Otherwise insert an element into the rear of the deque] else DQ[rear] = item (d) [Increment the rear pointer by one] rear = rear + 1 (e) End. (B) Equivalent C Function /* Function to add an item to the rear of the deque Input : deque and item Effect : item is added on the rear of the deque */ void add_at_rear(deque *DQ, int item) { if (DQ->rear >= DQSIZE) { printf("Deque is full at the rear end.!\n"); return; } if ((DQ->front == 0) &&(DQ->rear == 0)) { DQ->element[DQ->rear] = item; DQ->rear = DQ->rear +1; } else

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

174 Data Structures

{ DQ->element[DQ->rear] = item; DQ->rear = DQ->rear +1; } } (iii) Delete from Front Operation : This operation deletes or removes the item from the front of the deque. (A) Algorithm : Following are the steps for delete operation from rear of a deque : (a) [Check underflow condition] If (rear == 0) && (front == 0) then print underflow and return (b) [Otherwise assign element from the front of the deque to item and increment front by one] else Set item := DQ[front] front =front +1 (c) [Check for empty deque] If(front =rear) then Set front := 0, rear :=0 (d) [Return item from the front of the deque] return(item) (e) End. (B) Equivalent C Function /* Function to delete an item from the front of the deque Input : deque and item Output : return item from the front of the deque */ int delete_from_front (deque *DQ, int item) { if ((DQ->front == 0) && (DQ->rear == 0)) { printf("Underflow!!!\n"); return(0); } else { item = DQ->element[DQ->front]; DQ->front = DQ->front +1; } if (DQ->front==DQ->rear) { DQ->front =0; DQ->rear = 0; } return item; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 175

(iv) Add at Front Operation : This operation adds an element at the front of the deque. (A) Algorithm : Following are the steps for add operation at front of a deque : (a) [Check overflow condition] If (front<=0) then print overflow and return (b) If(front >0) then decrement the front pointer by one front = front - 1 (c) [Insert an element in to the front of the deque] DQ[front] = item (d) End. (B) Equivalent C Function /* Function to add an item at the front of the deque Input : deque and item Effect : item is added on the front of the deque */ void add_at_front(deque *DQ, int item) { if (DQ.front <=0) { printf("deque is full at the front end.!\n"); return; } if(DQ->front > 0) { DQ->front = DQ->front-1; DQ->element[DQ->front] = item; } } (v) Delete from Rear Operation : This operation deletes or removes the item from the rear of the deque. (A) Algorithm : Following are the steps for delete operation from rear of a deque : (a) [Check underflow condition] If (rear == NULL) then print underflow and return (b) [Otherwise decrement rear by one and assign element from the rear of the deque to item] else Set rear = rear -1 item := DQ[rear] (c) [Check deque for single element] If(front =rear) then Set front := 0, rear :=0 (d) [Return item from the rear of the deque] return(item) (e) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

176 Data Structures

(B) Equivalent C Function /* Function to delete an item from the rear of the deque Input : deque and item Output : return item from the rear of the deque */ int delete_from_rear(deque *DQ, int item) { if (DQ->rear == 0) // Deque already empty { printf("Underflow!!!\n"); return(1); } else { DQ->rear = DQ->rear -1; item = DQ->element[DQ->rear]; } if (DQ->front==DQ->rear) //Deque has only one item { DQ->front =0; DQ->rear = 0; } return item; } 2.18.3 Implementation of Deque Operations Using Array : The following program deque_operation.c shows the array implementation of all the operations of deque in numbers : /* Implementation of deque operations using array */ /* deque_operation.c */ #include<stdio.h> #include<stdlib.h> #define DQSIZE 100 typedef struct dq_tag { int front,rear; int element[DQSIZE]; }deque; void initialise(deque *); void display(deque *); void add_at_rear(deque *, int); void add_at_front(deque *, int); int delete_from_front(deque *, int); int delete_from_rear(deque *, int);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 177

void main() { int x,item,choice; deque DQ; initialise(&DQ); printf("This program performs the deque addition and deletion operations on numbers!\n"); printf("###############Menu#############\n"); printf("\n1: Insert an item at rear of the deque"); printf("\n2: Insert an item at front of the deque"); printf("\n3: Delete an item from front of the deque"); printf("\n4: Delete an item from rear of the deque"); printf("\n5: End. "); do { printf("\nPlease enter choice\n"); scanf("%d",&choice); switch(choice) { case 1: if (DQ.rear >= DQSIZE) { printf("deque is full at the rear end.!\n"); continue; } else { printf("Enter number to be added at rear\n"); scanf("%d",&item); add_at_rear(&DQ,item); printf("Entered elements in a deque are:-"); display(&DQ); continue; } case 2: if (DQ.front <=0) { printf("deque is full at the front end.!\n"); continue; } else { printf("Enter number to be added at front\n");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

178 Data Structures

scanf("%d",&item); add_at_front(&DQ,item); printf("Entered elements in a deque are:-"); display(&DQ); continue; } case 3: x = delete_from_front(&DQ,item); if (DQ.front==0) { continue; } else { printf("Entered elements in a deque are:-"); display(&DQ); continue; } case 4: x = delete_from_rear(&DQ,item); if (DQ.rear==0) { continue; } else { printf("Entered elements in a deque are:-"); display(&DQ); continue; } case 5: printf("End."); return; } }while(choice!=5); } void initialise(deque *DQ) { DQ->front=0; DQ->rear =0; } void add_at_rear(deque *DQ, int item) { if ((DQ->front == 0) &&(DQ->rear == 0)) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 179

DQ->element[DQ->rear] = item; DQ->rear = DQ->rear +1; } else { DQ->element[DQ->rear] = item; DQ->rear = DQ->rear +1; } } int delete_from_front(deque *DQ, int item) { if ((DQ->front == 0) && (DQ->rear == 0)) { printf("Underflow!!!\n"); return(0); } else { item = DQ->element[DQ->front]; printf("Number is deleted from front: %d\n",item); DQ->front = DQ->front +1; } if (DQ->front==DQ->rear) { DQ->front =0; DQ->rear = 0; printf("Now deque is empty!\n"); printf("There is no element(front end) in a deque.\n"); } return item; } void add_at_front(deque *DQ, int item) { if(DQ->front > 0) { DQ->front = DQ->front-1; DQ->element[DQ->front] = item; } } int delete_from_rear(deque *DQ, int item) { if (DQ->rear == 0) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

180 Data Structures

printf("Underflow!!!\n"); return(0); } else { DQ->rear = DQ->rear -1; item = DQ->element[DQ->rear]; printf("Number is deleted from rear: %d\n",item); } if (DQ->front==DQ->rear) { DQ->front =0; DQ->rear = 0; printf("Now deque is empty!\n"); printf("There is no element(rear end) in a deque.\n"); } return item; } void display(deque *DQ) { int x; x = DQ->front; for(x;x<DQ->rear;x++) { printf("%d\t",DQ->element[x]); } printf("\n"); } Output of the Program This program performs the deque addition and deletion operations on numbers! ###############Menu############# 1: Insert an item at rear of the deque 2: Insert an item at front of the deque 3: Delete an item from front of the deque 4: Delete an item from rear of the deque 5: End. Please enter choice 1 Enter number to be added at rear 12 Entered elements in a deque are:-12

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 181

Please enter choice 1 Enter number to be added at rear 23 Entered elements in a deque are:-12 Please enter choice 2 deque is full at the front end.! Please enter choice 1 Enter number to be added at rear 34 Entered elements in a deque are:-12 Please enter choice 1 Enter number to be added at rear 45 Entered elements in a deque are:-12 Please enter choice 1 Enter number to be added at rear 56 Entered elements in a deque are:-12 Please enter choice 3 Number is deleted from front: 12 Entered elements in a deque are:-23 Please enter choice 4 Number is deleted from rear: 56 Entered elements in a deque are:-23 Please enter choice 2 Enter number to be added at front 12 Entered elements in a deque are:-12 Please enter choice 3 Number is deleted from front: 12 Entered elements in a deque are:-23 Please enter choice 4 Number is deleted from rear: 45

23

23

34

23

34

45

23

34

45

56

34

45

56

34

45

23

34

45

34

45

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

182 Data Structures

Entered elements in a deque are:-23 34 Please enter choice 3 Number is deleted from front: 23 Entered elements in a deque are:-34 Please enter choice 4 Number is deleted from rear: 34 Now deque is empty! There is no element(rear end) in a deque. Please enter choice 3 Underflow!!! Please enter choice 4 Underflow!!! Please enter choice 5 End.

2.19 PRIORITY QUEUE
One of the application of the queue is the priority queue. A queue in which it is possible to add an item or delete an item at any position depending on the some priority is called priority queue. Many application involving queues require priority queues rather than the simple FIFO strategy. Each queue element has an associated priority value and the elements are served on a priority basis instead of using the order of arrival. For elements of same priority, the FIFO order is used. For example, in a multi-user system, there will be several programs competing for use of the central processor at one time. The programs have a priority value associated to them and are held in a priority queue. The program with the highest priority is given first use of the central processor. Often the items added to a queue have a priority associated with them, this priority determines the order in which they exit in the queue. Highest priority items are removed first. This situation arises often in process control systems. Imagine the operator's console in a large automated factory. It receives many routine messages from all parts of the system. They are assigned a low priority because they just report the normal functioning of the system. They update various parts of the operator's console display simply so that there is some confirmation that there are no problems. It will make little difference if they are delayed or lost.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 183

However, occasionally something breaks or fails and alarm messages are sent. These have high priority because some action is required to fix the problem (even if it is a mass evacuation because nothing can stop the imminent explosion!). Typically, such a system will be composed of many small units, one of which will be a buffer for messages received by the operator's console. The communication system places messages in the buffer so that communication links can be freed for further messages while the console software is processing the message. The console software extracts messages from the buffer and updates appropriate parts of the display system. Obviously, we want to sort messages on their priority so that we can ensure that the alarms are processed immediately and not delayed behind a few thousand routine messages while the plant is about to explode. Scheduling of jobs within a time-sharing system is another application of queues. In such a system many users may request processing at a time and computer time is divided among these requests. The simplest approach sets up one queue that stores all requests for processing. Computer processes the request at the front of the queue and finishes it before starting on the next. Same approach is also used when several users want to use the same output device, like a printer. LC1 1 LC2 … LCi-1 FM1 FM2 … FMj-1 CS1 CS2 … CSk-1 GU1 GU2 … GUl-1 4 3 4 4 GUl-1 CSk-1 2 3 3 FMj-1 1 2 2 LCi-1 1

Fig. 2.24 Priority Queue Job Waiting for Printer

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

184 Data Structures

In a time-sharing system, another common approach is used to process a job only for a specified maximum length of time. If the program is fully processed within that time, then the computer goes on to the next process. If the program is not completely processed within the specified time, the intermediate values are stored and the remaining part of the program is put back on the queue. This approach is useful in handling a composite of long and short jobs. Fig. 2.24 illustrates priority queue jobs waiting to use printer on a LAN system in a computer department of a college. Priorities of 1,2,3 and 4 have been assigned to the jobs of lab-coordinators, facultymembers, college-students and general-users, respectively. Therefore, if a job is initiated with priority p, it is inserted immediately at the end of the queue of other jobs with priority p, for p=1,2,3 and 4. Jobs are always removed from the front of the queue.

2.20 SIMULATION
Simulation is an area where queues can be applied. Simulation is the process of forming an abstract model from a real world situtation in order to understand the impact of modifications and the effect of introducing various strategies on the situation. The main purpose of the simulation program is to study the real life situation under control of various parameters, which affect the real problem, and is a research interest of systems analyst. It allows the user to expreiment with real and proposed situations otherwsie impossible or impractical. Simulation is a very powerful tool, if applied correctly. (i) Advantages (a) It permits experimentation without modifying the real situation. (b) Large numbers of alternative modifications to a situation may be included in a simulation and their results can be studied systematically in a comparative fashion. (ii) Disadvantages (a) Large detailed simulations are expensive to run on a computer. (b) The more simplifying the assumptions, the less reliable the results, weheras the more details included, generally the better the results. (c) The prediction obtained will be inaccurate if the initial assumptions are incorrect or the situation being studied changes over time. Any process or situation which is to be simulated is considered to be a system. A system is a collection of objects interacting in order to produce at least one output . A system can be divided into the following types :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 185

(i) Discrete System : If the parameters can only take values from a fixed number of choices. For example, customers arriving at a ticket counter. (ii) Continuous System : If the parameters can take any real value in some given interval. For example, water flowing through a pipe to a reservoir or emanating from it. (iii) Deterministic System : If the initial state and input to the system are known then final outcome can be predicated. For example, a calculator is a deterministic system. (iv) Stochastic System : It is based on randomness and there is no known predicate for its randomness. For example, number of students waiting in front of office window can not be predicated. In order to simulate a system, a model of the system must be produced. A model is a body of information used to present the system in a different form. There are two types of models : (i) Event Driven Simulation : In this model, the system changes its state whenever a new event arrives to the system or exits from the system. (ii) Time Driven Simulation : In this model, systems change its states with the change of time. A major element in solving a problem is the formation of a model,since the model is simpler than the system it represents. It must be kept in mind that the model is finite and therefore cannot produce reliable information on every aspect of the original system. In order to determine the structure of a model for some situation, the entities, attributes and activities of the system should be determined. EXERCISE Q.1. Write a menu-driven program to perform the following operations : (i) An array of integers of 8 elements contains the following data in the first 5 items: 12 23 34 45 56. Enter the data into a stack. (ii) Use push and pop operations on the array so that at the end of the operations the array should contain the following data : 12 23 34 45 56 67 78 89. (iii) Display the original and final position of the stack. Q.2. Write a menu-driven program to simulate the following stack operations using linked stack : (i) Create a stack with roll numbers and marks of 10 students. (ii) Delete the 4 elements of the stack and display the rest elements on the screen with proper headings. Q.3. Consider the following stack of fibonacci numbers : Stack: 0,1,1,2,3,5,___,___,___,___ (i) Describe the stack as the following operation takes place :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

186 Data Structures

(a) pop(stack, 5), (b) push(stack, num), (c) push(stack, num), (d) pop(stack, num). (ii) Describe the stack if the operation pop(stack, num) deletes 3. Q.4. Suppose the following stack of names is in memory where stack is allocated n=8 places: TOP = 5 Stack : BCA,MCA,MBA,BBA,MFT,___,___,___ Discuss the output of the following operations : (i) pop(stack,name1), (ii) pop(stack,name2), (iii) push(stack,name3), (iv) Do while (TOP!=0) pop(stack,name). Q.5. Write a program segment that uses a stack to read an integer and print all its prime divisors in ascending order. For example, with integer 1000 the output should be : 2,2,2,5,5,5 Q.6. Implement the following factorial algorithm with the help of stack : 1 fact(n) = n*fact(n-1) if n>1 if n=0 or n=1

Q.7. Consider the grammar : G = (VN,VT,S,P) Where VN = (<S>) VT = {a,b,c} P = {<S> ::= a<S>a <S>::=b<S>b <S>::=c} Implement it with the help of stack. Q.8. Translate the following infix expressions into its equivalent postfix expressions : (i) (A-B)*((C+D)/E), (ii) ((A+B)/C^((D-E)+F)), (iii) (A+B)^C-D/E*F-G, (iv) A-B^C+D/E+F*G, (v) A+B/C+D-E*F. Q.9. Translate the following infix expressions into its equivalent prefix expressions :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 187

(i) (A-B)*((C+D)/E), (ii) ((A+B)/C^((D-E)+F)), (iii) (A+B)^C-D/E*F-G, (iv) A-B^C+D/E+F*G, (v) A+B/C+D-E*F. Q.10. Evaluate the following expressions : (i) (10+3^2-8/2*6-7), (ii) (12-2^3+10/2+4*2), (iii) (3+4/2+5-3*4+3). Q.11. Consider the following postfix expression : (i) (5,3,+,2,*,6,9,7,-,/,-), (ii) (6,10,+,12,8,-,*,8,2,-,4,^,+). Translate each expression into infix notation and then evaluate. Q.12. Write an algorithm that translates an infix expression into polish prefix notation. Implement the designed algorithm with the help of stack. Q.13. Using stack algorithm convert each infix expression into its equivalent postfix expression : (i) (A-B)/((C+D)*E), (ii) ((A+B)/C)^(D-E)*F). Q.14. Using stack algorithm evaluate each postfix expression : (i) (3,5,+,6,4,-,*,4,1,-,2,^,+), (ii) (3,1,+,2,^,7,4,-,2,*,+,5,-). Q.15. Create a queue of 10 nodes based on the following structure : Struct { int tele_no[6]; char name[20]; }list; Perfrom the following operations : (i) to add a node, (ii) to delete a node, (iii) to display the queue after every operation. Q.16. Write a C-function to count the number of nodes in a queue. Q.17. Consider the following queue of characters, where queue is a circular array which is allocated 8 memory cells : FRONT = 3, REAR = 5 QUEUE: ___,___,C,D,E,___,___,___ (i) F is added to the queue, (ii) two letters are deleted, (iii) G,H and I are added to the queue, (iv) two letters are deleted, (v) J is added to the queue,

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

188 Data Structures

(vi) two letters are deleted, (vii) K is added to the queue, (viii) two letters are deleted, (ix) one letter is deleted, (x) one letter is deleted. Q.18. Suppose each data structure is stored in a circular array with N memory cells : (i) Find the number of elements in a queue in terms of FRONT and REAR. (ii) Find the number of elements in a queue in terms of LEFT and RIGHT. (iii) When will the array be filled? Q.19. Is it possible to implement a queue with the of two stacks? Q.20. Implement a deque with the help of linear linked list. Q.21. Design an algorithm for an input restricted deque. Implement the designed algorithm with the help C-function. Q.22. Design an algorithm for an output restricted deque. Implement the designed algorithm with the help C-function. Q.23. What is the practical use of circular queue? Give at least two examples and implement one of them. Q.24. Design an algorithm for an priority queue. Implement the algorithm with the help of C function and write a program for maintaining a list of waited job. Q.25. Consider the following deque where DEQUE is allocated 6 memory cells : FRONT = 2 REAR =5 DEQUE : ___, Ram, Mohan, Shyam, Krishan,___ (i) Gopal is added on the FRONT, (ii) two names are deleted from the REAR, (iii) Sonu is added on the FRONT, (iv) Shiv is added on the REAR, (v) two names are deleted from the REAR, (vi) a name is deleted from the FRONT, (vii) Raju is added on the FRONT. Q.26. Design an algorithm and write a function two concatenate two strings using recursion. Q.27. Write a program that takes integer number as input and displays reverse of the number on the screen. Use recursion to solve this problem. Q.28. What is the need of stack in implementing a recursive function? Q.29. Write a recursive function that trims all blanks from the front and rear of a string of text.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,     Pt. Ravishankar Shukla University,Raipur

 

2010 

Linked List, Stack and Queue 189

Q.30. Write a recursive function to compute the square root of a number. Q.31. Write a recursive function to convert decimal integers to their radix r representation by successive divisions. Q.32. Write a function using recursion to compute value of A(4,3) using Ackermann’s function. Q.33. Write a recursive function, which takes a floating number as input and display real and integer parts separately. Q.34. Write a program to create a singly linked list of records sorted in decending order. Key record is of type character. Q.35. Write a program to create a doubly linked list in descending sorted order of the information. Information field is of type character. Q.36. Write a program to print the information from each node in reverse order in doubly linked list. Q.37. Write a program for concatenating two linked lists. Q.38. Write a program for spiltting linked list in two.

**

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

3
3.1 INTRODUCTION

TREES

This chapter covers trees with its basic terminology, formal definition of the tree and types of the tree. In case of binary tree, chapter covers its definition, representation, operations, traversal of binary tree, threaded binary trees, conversion of general tree to binary tree and binary expression tree. It also covers application of trees, searching technique like- sequential search, binary search, height balanced trees, weight balanced trees and digital search trees. Searching technique hashing with various hashing functions and collisions handling techniques are also covered in this chapter.

3.2 BASIC CONCEPTS
The concept of trees is one of the most fundamental and useful concepts in computer science. Trees have many variations, implementations and applications. There are various applications, where tree structure is the efficient way to maintain and manipulate data, such as, compiler construction, database design, windows, operating system programs, etc. We can represent a tree as a structure consisting of nodes and edges, which represent a relationship between two nodes. Figure 3.1 shows a general tree. Level
1

0

2

3

4

1

5

6

7

8

9

2

Fig. 3.1 A General Tree

Here are some commonly used terms that apply to all trees : (i) Child : An immediate successor node is called a child of its predecessor. The leaf node has no children. (ii) Parent : An immediate predecessor node is called the parent of its children. The root node has no parent. (iii) Sibling : The nodes which have the same parent are called siblings. In fig. 3.1 5, 6 and 7 are siblings.
(190)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Trees 191

(iv) Leaf Node or Terminal Node or External Node : A node which is at the end and does not have any child(both pointer values are NIL) is called a leaf node. In fig. 3.1 5, 6, 7, 8 and 9 are the leaf nodes. It is also called terminal node. It is usually represented by the square. (v) Non Terminal Node or Internal Node : Nodes with at least one child is sometimes called non terminal node. The circle usually represents non-terminal node. (vi) Level : The number of pointer links required to move from a given node to the root node is called the level of that node. Figure 3.1 shows, the level of various nodes. (vii) Depth : The highest level number of any node in a tree is called the depth of the tree. (viii) Height : Maximum number of nodes which is possible in a path, starting from root to a leaf node is called the height of a tree. The height of a tree is obtained by : H = (Max Level) +1 In fig. 3.1, the height of the tree is 3. (ix) Ancestors and Descendents : If there is a path from node t1 to node t2, then t1 is ancestor of t2 and t2 is a descendent of t1. The root has no ancestor, and leaves have no descendent. (x) Degree : The maximum number of children, a node can have, is called the degree of the node. In fig. 3.1, degree of root node 1 is 1, node 2 is 3 and node 4 is 2.

3.3 TREE
Definition : Let us formally define a tree. A tree(T) is a non-empty finite collection of nodes or vertices, such that : (i) there is one specially designated vertex or node called root of the tree(T), (ii) the remaining nodes are partitioned into a collection of subtrees T1, T2,T3,…,Tn each of which is again a tree. Let us consider a tree T, as shown in figure 3.2.
1

2

3

4

5

6

7 Fig. 3.2 A Tree T

8

9

In this tree(T), 1 is the node called the root of the tree(T). T1, T2 and T3 are sub-trees of the tree(T). T1(with root 2), T2 (with root 3) and

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

T3(with root 4) are again trees by the definition of the tree. The tree(T) has total 9 nodes with 8 edges.
192 Data Structures

3.4 BINARY TREE
Perhaps the most commonly used type of tree data structure is binary tree. It is the simplest type to implement and can be very efficient, if used properly. Binary tree is a specific implementation of an m-ary tree, where m= 2, child nodes per node on the tree. In simpler terms, this means that each node on the tree contains two links to two other trees, both referred to as sub-trees. The two sub-trees are often called the left and right subtree. A binary tree is made of nodes that can have at most two children. The root node is the node that is not a child of any other node, and is found at the "top" of the tree structure. Definition : Let us formally define a binary tree. A binary tree(T) is a finite set of nodes such that : (i) T is empty called the null binary tree, (ii) T contains a distinguished node R called the root of T, and the remaining nodes of T form two ordered pairs of disjoints binary tree T1 and T2, which are called left sub-tree and the right sub-tree of R, respectively. Figure 3.3 shows a binary tree with 9 nodes represented by the letter B to L. B is the root of the binary tree(T). The left sub-tree of the root B consists of the nodes C, E and F and the right sub-tree of B consist of the nodes D, H, I, K and L.
B

C

D

E

F

H

I

K Fig. 3.3 Binary Tree

L

3.4.1 Types of Binary Tree : There are four types of binary tree : (i) complete binary tree, (ii) full binary tree, (iii) extended binary tree or 2-tree, (iv) binary search tree.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(i) Complete Binary Tree : A binary tree is a complete binary tree, if all of its level, except possibly the last, have the maximum number
Trees 193

of possible nodes and if all the nodes at the last level appear as far left as possible. Figure 3.4 shows a complete binary tree. Level
1

0

2

3

1

4

5

6

7

2 3

8

9

10

11

12

Fig. 3.4 A Complete Binary Tree

(ii) Full Binary Tree : A binary tree is said to be a full binary tree, if all of its level have the maximum number of possible nodes. Figure 3.5 shows a full binary tree. Level
1

0

2

3

1

4

5

6

7

2

8

9

10

11

12

13

14

15

3

Fig. 3.5 A Full Binary Tree

(iii) Extended Binary Tree or 2-Tree : A binary tree T is said to be extended binary tree or 2-tree if each node N has either 0 or 2 children. The nodes with 2 children are called internal nodes represented by the circle and the nodes with 0 children are called external

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

nodes represented by the square, respectively. Figure 3.6 shows the extended binary tree.
194 Data Structures

B

C

D

E

F

H

I

K

L

Fig. 3.6 Extended Binary Tree or 2-Tree

(iv) Binary Search Tree : A binary search tree is a binary tree which is either empty or satisfies the following rules : (a) The info of the key in the left sub-tree is less than the info of the root. (b) The info of the key in the right sub-tree is more than or equal to the value of the root. (c) All the sub-trees of the left and right sub-tree observe the above two rules. Figure 3.7 shows the binary search tree.
60

30

70

20

55

65

75

18

26

35

57

62

Fig. 3.7 A Binary Search Tree

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

3.4.2 Representation of Binary Tree : It is often required to maintain trees in the computer memory. A binary tree must represent a hierarchical relationship between parent node and child nodes. There are two methods for representing binary tree. First is called the linear(sequential)
Trees 195

representation, using array and second is called as linked representation, using pointers. 3.4.2.1 Linear Representation of a Binary Tree : In this representation block of memory for an array is to be allocated before going to store the actual tree in it and once the memory is allocated, the size of the tree will be restricted as the memory permits. A sequential representation of a binary tree requires numbering of nodes, starting with nodes on level 0. The nodes are numbered from left to right. The nodes of the binary tree are maintained in a onedimensional array. Following are the rules, which easily determine the locations of the root, left child and right child of any node of a binary tree in the array. Let us assume that array index starts from 1 : (i) The root node is at position 1. (ii) For any node with index j, 1 < j ≤ m,(for some m) : (a) PARENT(j) = [j/2] For the node when j=1, j is the root and has no parent. (b) LEFTC(j) = 2 * j If 2 * j > m, then j has no left child. (c) RIGHTC(j) = 2 * j +1 If 2 * j +1 > m, then j has no right child. Let us consider the binary tree as shown in figure 3.8. The linear representation of the binary tree, using array is shown in figure 3.9. Level 0 1
B

Level 1

2

C

3

D

Level 2

E

4

5

F

6

H

7

I

Level 3

8

K

9

L

Fig. 3.8 Binary Tree 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

B

C

D

E

F

H

I

.

.

.

.

K

L

.

.

Fig. 3.9 Array Representation of the Binary Tree

Drawbacks : Except full binary tree the memory space remain unutilised in linear representation of a binary tree. It is also not possible to enhance
196 Data Structures

the tree structure if the array size is fixed. Insertion and deletion of a node requires considerable data movements up and down the array, which demand excessive amount of processing time. 3.4.2.2 Linked Representation of a Binary Tree : The problem associated with the linear representation of binary tree can be overcome through the use of the linked representation. In linked representation, each node consists of three fields as shown in figure 3.10. left info right

Fig. 3.10 Node Structure

In this structure, left and right fields store the link of left and right child of a node, respectively. The info field is used for storing information associated with the node. Let us consider the binary tree as shown in figure 3.11.
F

C

J

B

D

H

K

I Fig. 3.11 Binary Tree

Table 3.1 shows how linked representation may appear in memory of the binary tree, as shown in figure 3.11. Table 3.1 Linked Representation of Binary Tree
Address info left right

1 2 3 4 5 6

F B C D

4 0 3 0

7 0 6 0

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

7 8 9 10 11

J H I K

9 0 0 0

11 10 0 0
Trees 197

Figure 3.12 shows the logical view of the linked representation of a binary tree shown in figure 3.11. ROOT will contain the location of the parent node of binary tree. If any sub-tree is empty, then the corresponding pointer will contain the null value. If the binary tree itself is empty, then ROOT will contain the null value. ROOT
F

C

J

B

D

H

K

I Fig. 3.12 Logical View of the Linked Representation of a Binary Tree

3.4.3 Binary Search Tree Operations : We can use the following structure to implement binary search tree operations : typedef char item; typedef struct binary_tag { item info; struct binary_tag *left; struct binary_tag *right; }BTree; Following are the operations, which can be performed on a binary search tree : (i) Insertion in a Binary Search Tree : To insert a node in a binary search tree, we must check whether the tree already contains any nodes. If tree is empty, the node is placed in the root node. If the tree is not empty, then the proper location is found and the added node becomes either a left or a right sub-tree of an existing node.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

The function continues recursively until either it finds a duplicate or it hits a dead end. If it determines that the value to be added belongs to the left sub-tree and there is no left node, it creates one. If a left node exists, then it begins its search with the sub-tree beginning at this node. If the function determines, that the value to be added belongs to the right sub-tree of the current node, a similar process occurs.
198 Data Structures

Figure 3.13 shows the insertion of node 64. In this case, search start from root node as 60-70-65 then halts when it finds the dead end. So node 64 occurred in the right part of the node 65. ROOT
60

30

70

20

55

65

18

26

35

57

62

64

Fig. 3.13 Insertion of Node 64

(A) Algorithm : The following are the steps, which are used for insertion operation in a binary search tree : (a) [Initialise pointer to the root node] Set pointer = root (b) [Check whether the tree is empty] If(pointer ==NULL) then Set pointer =(BTree *)malloc(sizeof(BTree)) pointer[left] = NULL, pointer[right] = NULL, pointer[info] = info (c) [Test for the left sub-tree] If(info<pointer[info])then call recursively binary_insert function for left sub-tree Set pointer[left] = binary_insert(pointer[left], info) (d) [Test for the right sub-tree] If(info>pointer[info])then call recursively binary_insert function for right sub-tree Set pointer[right] = binary_insert(pointer[right], info) (e) [Otherwise item is duplicate] write ‘item is duplicate’ (f) return(pointer)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(g) End. (B) Equivalent Function in C BTree *binary_insert(BTree *pointer, int info) { /*Check whether the tree is empty */ if(pointer==NULL)
Trees 199

{ pointer =(BTree *)malloc(sizeof(BTree)); pointer->left = NULL; pointer->right = NULL; pointer->info = info; } else /*Test for the left child*/ if(info < pointer->info) pointer->left = binary_insert(pointer->left,info); else /*Test for the right child*/ if(info >pointer->info) pointer->right = binary_insert(pointer->right,info); else /*Duplicate entry*/ printf("Duplicate entry\n"); return(pointer); } (ii) Searching in a Binary Search Tree : To search a particular node in a binary search tree. We start the search from the root node, and compare the root node with the searched node. If the values are equal the search is said to be successful and searched node is found in the tree. If the searched value is less than the value in the root node, then it must be in the left sub-tree and if there is no left sub-tree, the value is not in the tree i.e., the search is unsuccessful. If there is a left sub-tree, then it is searched in the same way. Similarly, if the searched value is greater than the value in the root node, the right sub-tree is searched. Fig. 3.14 shows the path(in shaded line) for searching of 57 in binary search tree. ROOT
60

30

70

20

55

65

18

26

35

57

62

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

38 Fig. 3.14 Searching of Node 57 200 Data Structures

(A) Algorithm : The following are the steps, which are used for search operation in a binary search tree : (a) [Initialise] Set pointer = root and flag =0 (b) [Search the node in a binary search tree] Repeat steps from (c) to (e) while(pointer !=NULL) and (flag==0) (c) [Search a node from the root] if(pointer[info] ==info) then Set flag =1, return(flag) (d) [Search a node in the left sub-tree] if(info<pointer[info])then Set pointer = pointer[left] (e) [Search a node in the right sub-tree] if(info>pointer[info])then Set pointer = pointer[right] (f) return(pointer) (g) End. (B) Equivalent Function in C int binary_search(BTree *pointer, int info) { /*Search the node in a binary search tree*/ while(pointer!=NULL) { /*Search a node at the root in a binary search tree*/ if(pointer->info == info) { flag=1; return(flag); } else /*Search a node in the left sub-tree*/ if(info <pointer->info) pointer = pointer->left; else /*Search a node in the right sub-tree*/ pointer = pointer->right; } return(flag);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

} (iii) Deletion in a Binary Search Tree : This operation is used to delete a node(N) from non-empty binary search tree(T). The node(N) deleted from the tree depends primarily on the number of children of node(N). There are three cases to consider in deleting a node from a binary search tree.
Trees 201

(a) If the node(N) is a leaf, just set its parent pointer to null and delete the node(N). The deleted node is now unreferenced and may be disposed off. Figure 3.15 shows deletion of leaf node 62. ROOT
60

30

70

20

55

65

18

26

35

57

62

38 Fig. 3.15 Deletion of Node 62

(b) If the node(N) has just one child, point the "grandparent" to its child and delete the node(N). Figure 3.16 shows the deletion of node 70. root
60

30

70

20

55

65

18

26

35

57

38

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.16 Deletion of Node 70

(c) If the node(N) has two children’s, then N is deleted by first deleting SUCC(N) from tree[using case1 or case2;it can be verified that SUCC(N) always occurs in the right sub-tree of node(N) and SUCC(N) never has a left child] and then replace the data content in node N by the data content in node SUCC(N). Figure 3.17 shows the deletion of 30.
202 Data Structures

ROOT

60

30

35

65

20

55

18

26

35

57

38 Fig. 3.17 Deletion of Node 30

Figure 3.18 shows the binary search tree after deletion of node 30. ROOT
60

35

70

20

55

65

18

26

38

57 Fig. 3.18 After deletion of node 30

(A) Algorithm : The following are the steps, which are used for deletion operation in a binary search tree : (a) [Initialise] Set flag =0 and pointer=root

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(b) [Search the node in a tree] Repeat steps from (c) to (e) while (pointer !=NULL) and (flag==0) (c) [Search a node from the root] If(pointer[info] ==info) then Set flag =1,
Trees 203

(d) [Search a node in the left sub-tree] If(info<pointer[info])then Set parent =pointer and pointer = pointer[left] (e) [Search a node in the right sub-tree] If(info>pointer[info])then Set parent =pointer and pointer = pointer[right] (f) [When the node does not exist] If(flag==0) then write ’info does not exist in the tree’ (g) [Decide the case of deletion] If(pointer[left] ==NULL) and (pointer[right]==NULL) then [Node has no child] Set case =1 else If(pointer[left] !=NULL) and (pointer[right]!=NULL) then [Node contains both the childs] Set case =3 else [Node contains only one child] Set case=2 (h) [Deletion when node has no child] If(case==1) then [Node is a left child] If(parent[left]=pointer) then Set parent[left]=NULL [Node is a right child] else Set parent[right]=NULL return(pointer) (i) [Deletion when node contains only one child] If(case==2) then [Node is a left child] If(parent[left]=pointer)then If(pointer[left]==NULL)then Set parent[left]=pointer[right] else Set parent[left]=pointer[left] else [Node is a right child]

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

If(parent[right]=pointer)then If(pointer[left]==NULL)then Set parent[right]=pointer[right] else Set parent[right]=pointer[left] return(pointer)
204 Data Structures

(j) [Deletion when node contains two childs] If(case==3) then [Find the in order successor of the node] Set pointer1=pointer[right] [Check right sub-tree is not empty] If(pointer1!=NULL)then Repeat while(pointer1[left]!=NULL) [Move to the left most end] pointer1=pointer1[left] Set item=pointer1[info] Call function binary_delete(pointer,item) for deletion of inorder successor [Replace the deleted node with the inorder successor of the node] Repeat while ((pointer !=NULL) and (flag==0)) [Search a node in the left sub-tree] If(info<pointer[info])then Set pointer = pointer[left] [Otherwise search a node in the right sub-tree] If(info>pointer[info])then Set pointer = pointer[right] [Otherwise search a node from the root] If(pointer[info] ==info) then Set flag =1 and pointer[info]=item return(pointer) (k) End. (B) Equivalent Function in C BTree *binary_delete(BTree *pointer, int info) { BTree *parent,pointer1; int flag=0,case,item1; /*Find the location of the node*/ while(pointer!=NULL) && (flag==0) { if(info <pointer->info)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

{ parent=pointer; pointer = pointer->left; } else if(info >pointer->info)
Trees 205

{ parent=pointer; pointer = pointer->right; } else flag=1; } /*When node does not exist*/ if(flag==0) { printf(“Node does not exist in the tree\n”); exit(0); } else /*Decide the case of deletion*/ { if(pointer->left ==NULL) && (pointer->right==NULL) /*Node has no child*/ case =1; else if(pointer-> !=NULL) && (pointer->right!=NULL) /*Node contains both the child*/ case =3; else /*Node contains only one child*/ case=2; } /* Deletion of node based on cases */ if(case==1) { /*Deletion when node has no child*/ if(parent->left=pointer) parent->left=NULL; else parent->right=NULL; return(pointer);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

} else /*Deletion when node contains only one child*/ if(case==2) { /*Node is a left child*/
206 Data Structures

if(parent->left=pointer) { if(pointer->left==NULL) parent->left=pointer->right; else parent->left=pointer->left; } else /*Node is a right child*/ if(parent->right=pointer) { if(pointer->left==NULL) parent->right=pointer->right; else parent->right=pointer->left; } return(pointer); } else /*Deletion when node contains two child*/ if(case==3) { /*Find the in order successor of the node*/ pointer1=pointer->right; /*Check right sub-tree is not empty*/ if(pointer1!=NULL) { while(pointer1->left!=NULL) /*Move to the left most end*/ pointer1=pointer1->left; } item=pointer1[info]; /* Delete inorder successor of the node*/ binary_delete(pointer,item); /*Replace the deleted node with the inorder successor of the node*/ while((pointer!=NULL) && (flag==0))

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

{ if(info <pointer->info) pointer = pointer->left; else if(info >pointer->info) pointer = pointer->right;
Trees 207

else { flag=1; pointer[info]= item; } } return(pointer); } }

3.5 TRAVERSALS OPERATION OF A BINARY TREE
Traversing a binary tree operation is used when we like to visit each node in the tree exactly once. The traversal on a binary tree gives the listing of the nodes of a tree in a certain order. Let us consider a binary tree as shown in figure 3.19.
F

C

J

B

D

H

K

I Fig. 3.19 Sorted Binary Tree

The tree can be traverse in four ways. These four types are as follows : 3.5.1 Preorder traversal : A preorder traversal, visits each node of a sorted tree, in preorder. In other words, the root node visits first, followed by left sub-tree and finally the right sub-tree. So, in figure 3.19, a preorder traversal would result in the following string : FCBDJHIK. (A) Algorithm : The following steps are used for preorder traversal operation of a binary tree :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(a) [Check the node is not empty] If(pointer != NULL) then (b) [visit the node] Visit(pointer) (c) [Call recursively for left sub-tree] Preorder(pointer[left]) (d) [Call recursively for right sub-tree]
208 Data Structures

Preorder(pointer[right]) (e) End. (B) Equivalent Function in C void Preorder(BTree * pointer) { if (pointer!= NULL) { printf("%3c",pointer->info); Preorder(pointer->left); Preorder(pointer->right); } } 3.5.2 Inorder Traversal : An inorder traversal, visits each node of a sorted tree, in inorder. In other words, the left sub-tree visits first, followed by root node and finally the right sub-tree. So, in figure 3.19, an inorder traversal would result in the following string : BCDFHIJK. (A) Algorithm : The following steps are used for inorder traversal operation of a binary tree : (a) [Check the node is not empty] If(pointer != NULL) then (b) [Call recursively for left sub-tree] Inorder(pointer[left]) (c) [visit the node] Visit(pointer) (d) [Call recursively for right sub-tree] Inorder(pointer[right]) (e) End. (B) Equivalent Function in C void Inorder(BTree * pointer) { if (pointer!= NULL) { Inorder(pointer->left); printf("%3c",pointer->info); Inorder(pointer->right); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

} 3.5.3 Postorder Traversal : A postorder traversal, visits each node of a sorted tree, in postorder. In other words, the left sub-tree visits first, followed by the right sub-tree and finally visits the root node of the tree. So, in figure 3.19, a postorder traversal would result in the following string : ADCIHKJF.
Trees 209

(A) Algorithm : The following steps are used for postorder traversal operation of a binary tree : (a) [Check the node is not empty] if(pointer != NULL) then (b) [Call recursively for left sub-tree] Postorder(pointer[left]) (c) [Call recursively for rigth sub-tree] Postorder(pointer[right]) (d) [visit the node] Visit(pointer) (e) End. (B) Equivalent Function in C void Postorder(BTree * pointer) { if (pointer!= NULL) { Postorder(pointer->left); Postorder(pointer->right); printf("%3c",pointer->info); } } 3.5.4 Level by Level Traversal : In this method, we traverse level-wise i.e., we first visit node at level '0' i.e., root. Then we visit nodes at level ‘1’ from left to right and so on. It is same as breadth first search. This traversal is different from other three traversals in the sense that it needs not be recursive, therefore, we may use queue kind of a data structure to implement it. For example the level by level traversal of the binary tree given in figure 3.19 would result in the following string : FCJBDKHI. 3.5.5 Implementation of the Traversal Operations of Binary Tree : The following program tree_traveral.c shows the implementation of traversal operations of the binary tree : /*tree_traversal.c*/ #include<stdio.h>

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

#include<malloc.h> typedef struct binary_tag { char info; struct binary_tag *left; struct binary_tag *right; }BTree;
210 Data Structures

BTree *Binary_Tree( BTree *,char); void Prerder(BTree *); void Inorder(BTree *); void Postorder(BTree *); void main() { char ch,info; BTree *pointer; printf("!!!This program performs the traversal operations of a binary tree!!!\n"); printf("!!!Please enter the node infomation(a single character)of a tree in PRE ORDER!!!\n"); pointer = (BTree *)malloc(sizeof(BTree)); pointer = NULL; do { printf("Enter the information of the node:"); scanf("%c",&info); pointer=Binary_Tree(pointer,info); fflush(stdin); printf("Do you want to add some other node(enter 'y' for yes):"); scanf("%c",&ch); fflush(stdin); }while(ch=='y'); printf("!!!The followings are the output of the traversal operations\n!!!"); printf("\nPre order traversal of a binary tree is:"); Preorder(pointer); printf("\nInorder traversal of a binary tree is:"); Inorder(pointer); printf("\nPost order traversal of a binary tree is:"); Postorder(pointer); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

BTree *Binary_Tree( BTree *pointer,char info) { if(pointer==NULL) { pointer =(BTree *)malloc(sizeof(BTree)); pointer->left = NULL; pointer->right = NULL;
Trees 211

pointer->info = info; } else if(info < pointer->info) pointer->left = Binary_Tree(pointer->left,info); else if(info >pointer->info) pointer->right = Binary_Tree(pointer->right,info); else printf("Duplicate entry\n"); return(pointer); } void Preorder(BTree * pointer) { if (pointer!=NULL) { printf("%3c",pointer->info); Preorder(pointer->left); Preorder(pointer->right); } } void Inorder(BTree * pointer) { if (pointer != NULL) { Inorder(pointer->left); printf("%3c",pointer->info); Inorder(pointer->right); } } void Postorder(BTree * pointer) { if (pointer!= NULL) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Postorder(pointer->left); Postorder(pointer->right); printf("%3c",pointer->info); } } Output of the Program !!!This program performs the traversal operations on a binary tree!!!
212 Data Structures

!!!Please enter the node infomation(a single character)of a tree in PRE ORDER!!! Enter the information of the node:f Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:c Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:b Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:d Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:j Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:h Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:i Do you want to add some other node(enter 'y' for yes):y Enter the information of the node:k Do you want to add some other node(enter 'y' for yes):n !!!The followings are the output of the traversal operations!!! Pre order traversal of a binary tree is: f c b d j h i k Inorder traversal of a binary tree is: b c d f h i j k Post order traversal of a binary tree is: b d c i h k j f

3.6 THREADED BINARY TREE
In the linked representation of a binary tree approximately half of the entries in the link fields are with null values and thereby wasting the memory space. A. J. Perlis and C. Thornton devised a way to utilise these null value link fields. Their idea is to replace certain null entries by special pointers, which point to nodes higher in the tree. These special pointers are called threads, and binary tree with such pointers is called threaded binary tree. 3.6.1 Representation of Threaded Binary Tree : In the representation of a threaded binary tree the problem is of distinguishing a link from a thread. In computer memory, an extra 1-bit TAG field may be used to

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

differentiate threads from ordinary pointers, or, alternatively, threads may be denoted by negative integers when ordinary pointers are denoted by positive integers. There are three ways to thread a binary tree, these correspond to inorder, preorder and postorder traversal. One may also select a oneway threading or a two-way threading. Unless otherwise stated, our threading will correspond to the inorder traversal of tree.
Trees 213

In one-way threading of tree, a thread will appear in the right field of a node and will point to the next node in the inorder traversal of tree. Figure 3.20 shows one-way inorder threading.

Fig. 3.20 One-way Inorder Threading

In two-way threading of tree, a thread will appear in the left field of a node and will point to the preceding node in the inorder traversal of tree. Figure 3.21 shows two-way inorder threading.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.21 Two-way Inorder Threading

When tree does not have a header node then the left pointer of the first node and the right pointer of the last node will contain the null value. Otherwise, it will point to the header node. Figure 3.22 shows twoway inorder threading with header node.
214 Data Structures

Fig. 3.22 Two-way Threading with Header Node

3.6.2 Advantages of Threaded Binary Tree : The following are the advantages of the threaded binary tree : (a) The traversal operation in threaded binary tree is faster than that of its unthreaded binary tree because non-recursive implementation of threaded binary tree is possible. (b) We can efficiently determine the predecessor and successor nodes starting from any node. (c) Node can be easily accessible from other node. (d) Implementations of insertion and deletion operations are very easy.

3.7 BINARY EXPRESSION TREE

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

A Binary tree is called an expression binary tree if it stores arithmetic expression. All internal nodes are operators and the leaves are operands of the binary expression tree. Fig. 3.23 shows the binary expression tree of the arithmetic expression : E = (B-C)+(E/F)*D
Trees 215

+

-

*
C / D

B

E
Fig. 3.23 Binary Expression Tree

F

3.8 CONVERSION OF GENERAL TREE TO BINARY TREE
Let T is a general tree. The following is the procedure for converting a general tree T to binary tree T’ : (i) All the nodes of the general tree(T) are also the nodes of the binary tree T’. (ii) The root of the general tree(T) is also the root of the binary tree(T’). (iii) Let N be an arbitrary node of the binary tree(T’) then the left child of N in T’ will be the first child of the node N in the general tree(T) and the right child of N in binary tree(T’) will be the next sibling of N in the general tree(T). Let us consider the general tree, as shown in figure 3.24. The corresponding binary tree is shown in figure 3.25.

a

b

c

d

e

f

g

h

i

j

k

l

n

p

q

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.24 A General Tree 216 Data Structures a

b

e

c

f

h

d

g

i

j

k

l

p

n

q Fig. 3.25 Equivalent Binary Tree

3.9 APPLICATIONS OF TREE
In this topic, we cover three applications. First, describes the Huffman coding. Second, describes the decision tree and third is game tree. 3.9.1 Huffman Coding : Huffman codes belong to a family of codes with a variable length codes, i.e., individual symbols, which make a message, are represented with bit sequences of distinct length. This characteristic of the code words helps to makes data compression possible. For example, symbols A, B, C and D are represented by following code words :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Symbol

Code Word

A B C D

0 10 110 111
Trees 217

At the first look it seems that the code words are not uniquely decodable. But, the power of Huffman codes is in the fact that all code words are uniquely decodable. So the sequence of bits : 0111100110 is uniquely decodable as ‘ADBAC’. Decreasing of redundancy in data by Huffman codes is based on the fact that distinct symbols have distinct frequencies of incidence. This fact helps to create such code words, which really contribute to decreasing of redundancy i.e., to data compression. Huffman's Algorithm : This coding system algorithm was given by Huffman in 1952. The algorithm for building Huffman code is based on the coding tree. The following are the steps : (a) Line up the symbols by falling frequencies. (b) Link two symbols with least frequencies, into one new symbol with frequency probability as a sum of frequencies of two symbols. (c) Go to step (b) until we generate a single symbol with frequency 1. Let us take an example how to build a set of Huffman codes. Let us consider the 10 data items, which has the following frequencies : Data Item : A B C D E F G H I J Frequencies : ⋅20 ⋅03 ⋅16 ⋅12 ⋅02 ⋅08 ⋅06 ⋅05 ⋅18 ⋅10 Figure 3.26(a) to (h) shows how to construct the tree using the above algorithms. In figure 3.26(a) each data item belongs to its own sub-tree and the two sub-trees with smallest frequencies are shaded.
A B C D E F G H I J

⋅20

⋅03

⋅16

⋅12

⋅02

⋅08

⋅06

⋅05

⋅18

⋅10

Fig. 3.26(a)

In figure 3.26(b) the two shaded sub-trees with smallest frequencies are joined together to form a sub-tree with frequency ⋅05.
A C D

⋅20

⋅16

⋅12

⋅05

F

G

H

I

J

⋅08

⋅06

⋅05

⋅18

⋅10

B

E

⋅03

⋅02

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.26(b)

Again, the current two sub-trees of lowest frequencies are joined and this process of joining of two sub-trees with lowest frequencies is continued as shown in figure 3.26(c) to (i).
218 Data Structures A C D F G I J

⋅20

⋅16

⋅12

⋅10

⋅08

⋅06

⋅18

⋅10

H

⋅05

⋅05
B E

⋅03

⋅02
Fig. 3.26(c)

A

C

D

⋅20

⋅16

⋅12

⋅10

I

J

⋅14

⋅18

⋅10

H

⋅05

F

G

⋅05
B E

⋅08

⋅06

⋅03
A C D

⋅02
Fig. 3.26(d) I

⋅20

⋅16

⋅12

⋅20

⋅14

⋅18

⋅10

J

F

G

⋅10
H

⋅08

⋅06

⋅05

⋅05
B E

⋅03

⋅02

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.26(e) Trees 219

A

C

I

⋅20

⋅16

⋅20

⋅26

⋅18

⋅10

J

D

⋅14

⋅10

⋅12

H

⋅05

F

G

⋅05

⋅08

⋅06

B

E

⋅03

⋅02
Fig. 3.26(f)

A

⋅20

⋅34

⋅20

⋅26

C

I

⋅10

J

D

⋅14

⋅16

⋅18

⋅10

⋅12

H

⋅05

F

G

⋅05

⋅08

⋅06

B

E

⋅03

⋅02

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.26(g) 220 Data Structures

⋅34

⋅40

⋅26

C

I

A

⋅20

D

⋅14

⋅16

⋅18

⋅20

⋅12

⋅10

J

F

G

⋅10

⋅08

⋅06

H

⋅05

⋅05
B E

⋅03

⋅02
Fig. 3.26(h)

⋅40

⋅60

A

⋅20

⋅34

⋅26

⋅20 ⋅10
J C I D

⋅10
H

⋅14

⋅16

⋅18

⋅12

⋅05
F B E G

⋅05

⋅08

⋅06

⋅03

⋅02

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Fig. 3.26(i) Trees 221

Figure 3.26(j) shows the final tree formed when only two remaining sub-trees are joined together.
1

⋅40

⋅60

A

⋅20

⋅34

⋅26

⋅20 ⋅10
J C I D

⋅10
H

⋅14

⋅16

⋅18

⋅12
F G

⋅05 ⋅08
B E

⋅05

⋅06

⋅03

⋅02
Fig. 3.26(j)

3.9.2 Decision Tree : Rooted trees can be used to model problems in which a series of decisions leads to a solution. For example, a binary search tree can be used to locate items based on a series of comparisons where each comparison tells us whether we have located the item, or whether we should go down the left or right sub-tree. More generally, we may have a rooted tree in which each internal node corresponds to a decision. At each such node, we may have a number of children (i.e., sub-trees) that correspond to each possible outcome of the decision. Such a tree is called a decision tree. The possible solutions to a problem (i.e., set of choices that may be taken in the problem) correspond to the distinct paths from the root to the leaves of the tree.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

3.9.3 Game Tree : Consider a two-player game. A solution to the game is a sequence of their alternate moves, which leads one of them to win. The solution space is the set of all possible solutions. A rooted tree called a game tree is a useful representation of the solution space. In the game tree, a solution corresponds to a path from the root to a leaf.
222 Data Structures

On the path, edges correspond to moves of two players alternately. Suppose that you play first and the opponent plays next. Then, edges from nodes at even levels to nodes at odd levels correspond to your moves. You may try to maximise some objective function, which is associated with likelihood of your winning. On the other hand, edges from nodes at odd levels to nodes at even levels correspond to the opponent's moves. The opponent tries to minimise the objective function so as to minimise the likelihood of your winning and hence to maximise the likelihood of his/her winning.

3.10 SEQUENTIAL OR LINEAR SEARCH
The search of a list of items in consecutive order, by examining each item in the list in turn is called a linear or, sequential search. The most straightforward solution to this problem is to start with the lowest array index, and compare the value of the separately held item in question systematically to every item in the array to see if it is equal to one of them. A linear search does not depend for its success on the items being searched already being in any particular order. The value being sought will either be equal to one of the ones already in the array, or it will not. If it is, the index number of the position at which it is found can be returned. Otherwise, some indication that the search has failed must be passed back. Let us consider the following list of numbers : 11 34 23 45 38 10 56 36 27 67 (I) search the element 38, (II) search the element 40. (I) Search the Element 38 : In this technique, the searched item is compared with all the items of the array one by one, i.e., element 38 is compared to the first element 11, which is not equal to 38. Now, 38 is compared with next element, i.e., 34. It is also not equal to 38. This process continues till we reach the end of the list or the searched element is found in the list. The element 38 is found in the list at position 4. So, the search is successful and returns the position of the element within the list, i.e., 4. (II) Search the Element 40 : In this technique, the searched item is compared with all the items of the array one by one, i.e., element 40 is compared to the first element 11, which is not equal to 40. Now, 40

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

is compared with next element, i.e., 34. It is also not equal to 40. This process continues till we reach the end of the list or the searched element is found in the list. The element 40 is not found in the list. So, the search is unsuccessful and returns the element, which is not found in the list. The following is the algorithm, which implements the above processing of searching :
Trees 223

(A) Algorithm : Let LIST be a linear array with n elements and ITEM is a given element of information. This algorithm finds the position(POS) of ITEM in LIST, if the search is successful or sets POS=0. If the searched item is not found in the list, it means search is unsuccessful. Following are the steps for sequential search algorithm : (a) [Initialise counter] Set (counter) i=1, POS=0 (b) [Search element] Repeat Step (c) and (d) while(POS==0 || i<=n) (c) [Compare searched ITEM with each element of the LIST] If ITEM == LIST[i] then the search is successful & print the ITEM is found in the list at POS Set POS = i , i = i + 1 and continue (d) Otherwise Set i = i+1, if(i==n) then break (e) If POS == 0 then print ‘ITEM is not found in the array LIST & search is unsuccessful’ (f) End. (B) Equivalent Function in C void sequential_search(int LIST[], int n, int ITEM) { int i=1, POS; POS = 0; while((i<=n) || (POS==0)) { if(ITEM == LIST[i]) { POS = i; printf("The search item %d is found in the LIST at position %d.\n",ITEM, POS); i = i +1; continue; } else i = i +1;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

if(i==n) break; } if(POS == 0) printf("The searched item %d is not found in the LIST.\n ",ITEM); }
224 Data Structures

(C) Implementation of Sequential Search Function : The following program search_sequential.c implements the sequential search function using the array LIST : /* search_sequential.c*/ #include<stdio.h> void sequential_search( int[],int,int); void main() { int i,n,LIST[100],ITEM; printf("This program search the specified ITEM in the LIST and return the position(POS) of the ITEM, (if found) using sequential search!!!\n"); printf("Please enter the number of elements in the LIST:\n"); scanf("%d",&n); printf("Enter the element of the LIST:\n"); for (i=1;i<=n;i++) { scanf("%d",&LIST[i]); } printf("Element to be searched:\n"); scanf("%d",&ITEM); printf("Entered elements in the LIST are:\n"); for (i=1;i<=n;i++) { printf("%d\t",LIST[i]); } sequential_search(LIST,n,ITEM); } void sequential_search(int LIST[], int n, int ITEM) { int i=1, POS; POS = 0; while((i<=n) || (POS==0)) { if(ITEM == LIST[i])

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

{ POS = i; printf("\nThe search item %d is found in the LIST at position %d.\n",ITEM, POS); i = i +1; continue; }
Trees 225

else i = i +1; if(i==n) break; } if(POS == 0) printf("\nThe searched item %d is not found in the LIST.\n",ITEM); } (D) Output of the Program This program search the specified ITEM in the LIST and return the position(POS) of the ITEM, (if found) using sequential search!!! Please enter the number of elements in the LIST: 10 Enter the element of the LIST: 12 23 34 45 56 67 78 89 90 23 Element to be searched: 23 Entered elements in the LIST are: 12 23 34 45 56 67 78 89 90 23 The search item 23 is found in the LIST at position 2. The search item 23 is found in the LIST at position 10. This program search the specified ITEM in the LIST and return the position(POS) of the ITEM, (if found) using sequential search!!! Please enter the number of elements in the LIST: 5

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

Enter the element of LIST: 12 23 21 34 43 Element to be searched: 29
226 Data Structures

Entered elements in the LIST are: 12 23 21 34 43 The searched item 29 is not found in the LIST. (E) Analysis of Sequential Search Method : Let's examine how long it will take to find an item matching a key in the LIST we have discussed so far. We are interested in : (i) the average time. (ii) the worst-case time. (iii) the best possible time. However, we will generally be most concerned with the worstcase time as calculations based on worst-case times can lead to guaranteed performance predictions. Conveniently, the worst-case times are generally easier to calculate than average times. If there are n items in our LIST, whether it is stored as an array or as a linked list, then it is obvious that in the worst case, when there is no item in the LIST with the desired key, then n comparisons of the key with keys of the items in the LIST will have to be made. To simplify analysis and comparison of algorithms, we look for a dominant operation and count the number of times that dominant operation has to be performed. In the case of searching, the dominant operation is the comparison, since the search requires n comparisons in the worst case, we say this is a O(n) (pronounce this "big-Oh-n" or "Ohn") algorithm. The best case in which the first comparison returns a match, requires a single comparison and is O(1). The average time depends on the probability that the key will be found in the LIST, this is something that we would not expect to know in the majority of cases. Thus, in this case, as in most others, estimation of the average time is of little utility. If the performance of the system is vital, i.e., it's a part of a life-critical system, then we must use the worst case in our design calculations as it represents the best guaranteed performance.

3.11 BINARY SEARCH
However, if we place our items in an array and sort them in either ascending or descending order on the key first, then we can obtain much better performance with an algorithm called binary search.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

In binary search, we first compare the key with the item in the middle position of the array. If there's a match, we can return immediately. If the key is less than the middle key, then the item sought must lie in the lower half of the array; if it's greater then the item sought must lie in the upper half of the array. So we repeat the procedure on the lower (or upper) half of the array. There are two termination conditions in binary search : (i) If low > high then the partition to be searched has no elements in it,
Trees 227

(ii) If there is a match with the element in the middle of the current partition, then we can return immediately. Let us take some examples for explaining the processing of binary search method. Let us consider the following sorted list of numbers : 11, 21, 46, 52, 55, 67, 79, 81, 86, 97, 99 (I) Search for the value 81 (a) The terms are numbered from 0 .. 10. The first search position is 5((0+10)/2=5), at which is found the number 67. The value 81 is compared to it and 81 is greater than 67(81>67). (b) Next the items from position 6 through 10 are considered. These are 79, 81, 86, 97, 99. Here, the search position is 8((6+10)/2=8) at which is the number 86, and 81 is less than 86(81<86). (c) Thus the list is reduced to items 6 through 7. The remaining list is 79, 81. The search position item is the first one holding 79, and 81 is greater than 79(81>79). (d) All that remains is the list with item 6 or 81 in it. The one wanted is equal to 81, and so has been found. So the search item 81 is found in the list. The following table 3.2 tabulates the processing steps of the searching. TABLE 3.2
Range List Position Result New range

[0 .. 10] the whole list 5 (67) greater [0 .. 4] [0 .. 4] 79, 81, 86, 97, 99 8 (86) less [6 .. 7] [3 .. 4] 79, 81 6 (79) greater [7 .. 6] success (II) Search for 50 in the list (a) The terms are numbered from 0 .. 10. The first search position is 5((0+10/2=5), at which is found the number 67. The value 50 is compared to it and 50 is less than 67(50<67). (b) Next, the items from position 0 through 4 are considered. These are 11, 21, 46, 52, 55. Here, the search position is 2((0+4)/2=2) at which is the number 46, and 50 is greater than 46(50>46).

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(c) Thus, the list is reduced to items 3 through 4. The remaining list is 52, 55. The search position item is the first one holding 52, and 50 is less than 52(50<52). (d) All that remains is the list with item 4 or 55 in it. The one wanted is not equal to 55, and so has been not found. The bottom counter would be greater than the top counter; there would be no list left, and the search would fail and the item 50 is not found in the list. The following table 3.3 tabulates the processing steps of the searching :
228 Data Structures

TABLE 3.3
Range List Position Result New range

[0 .. 10] [0 .. 4]

the whole list 11, 21, 46, 52, 55

5 (67) 2 (46)

less greater

[0 .. 4] [3 .. 4]

[3 .. 4] 52, 55 3 (52) less [4 .. 3] fails The following is the algorithm, which implement the above processing of searching : (A) Algorithm : Let LIST be a sorted linear array with n elements and ITEM is a given element of information. The variables BEG, END and MID denotes the beginning, end and middle position of the elements of LIST, respectively. This algorithm finds the position POS of ITEM in LIST, if the search is successful or sets POS=0. If the searched item is not found in the list i.e., search is unsuccessful. The following are the steps for binary search algorithm : (a) [Initialise counter] Set (counter) BEG=0, END = n, POS=0 (b) [Search element] Repeat Step (c) to (f) while(POS==0 && END>=BEG) (c) [Find the mid point of the LIST] MID = (BEG+END)/2 (d) [Compare searched ITEM with the item at mid of the LIST] If ITEM == LIST[MID] then the search is successful Set POS = MID and break (e) [Otherwise, check whether or not searched ITEM is less than the mid item of the LIST] If ITEM < LIST[MID] then Set END = MID –1 (f) [Otherwise, check whether or not searched ITEM is greater than the mid item of the LIST] Set BEG = MID +1 (g) If POS==0 then Print ‘ITEM is not found in the array LIST and search is

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

unsuccessful’ (h) [Otherwise search is successful] Print ‘search is successful and item is found in the LIST at position POS’ (i) End. (B) Equivalent Function in C void binary_search(int LIST[], int n, int ITEM) { int BEG,END,POS,MID;
Trees 229

BEG=1; END=n; POS = 0; while((BEG<=END) && (POS==0)) { MID = (BEG+END)/2; if(ITEM == LIST[MID]) { POS = MID; break; } else if(ITEM < LIST[MID]) END = MID - 1; else BEG = MID + 1; } if(POS == 0) printf("The searched item %d is not found in the LIST.\n",ITEM); else printf("The searched item%d is found in the LIST at position %d.\n",ITEM, POS); } (C) Implementation Of Binary Search Function : The following program search_binary.c implements the sequential search function using the sorted array LIST : /*search_binary.c*/ #include<stdio.h> void binary_search( int[],int,int); void main() { int i,n,LIST[100],ITEM;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

printf("This program searches the specified ITEM in the sorted LIST and returns the position(POS) of the ITEM, (if found) using binary search!!!\n"); printf("Please enter the number of elements in the LIST:\n"); scanf("%d",&n); printf("Enter the element of the LIST in ascending order:\n"); for (i=1;i<=n;i++) { scanf("%d",&LIST[i]);
230 Data Structures

} printf("Element to be searched:\n"); scanf("%d",&ITEM); printf("Entered elements in the LIST are:\n"); for (i=1;i<=n;i++) { printf("%d\t",LIST[i]); } binary_search(LIST,n,ITEM); } void binary_search(int LIST[], int n, int ITEM) { int BEG,END,POS,MID; BEG=1; END=n; POS = 0; while((BEG<=END) && (POS==0)) { MID = (BEG+END)/2; if(ITEM == LIST[MID]) { POS = MID; break; } else if(ITEM < LIST[MID]) END = MID - 1; Else BEG = MID + 1; } if(POS == 0) printf("The searched item %d is not found in the LIST.\n",ITEM);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

else printf("The searched item %d is found in the LIST at position %d.\n",ITEM, POS); } (D) Output of the Program This program searches the specified ITEM in the sorted LIST and returns the position(POS) of the ITEM, (if found) using binary search!!! Please enter the number of elements in the LIST: 10
Trees 231

Enter the element of the LIST in ascending order: 11 12 23 34 45 56 67 78 89 90 Element to be searched: 56 Entered elements in the LIST are: 11 12 23 34 45 56 67 78 89 90 The searched item 56 is found in the LIST at position 6. This program searches the specified ITEM in the sorted LIST and returns the position(POS) of the ITEM, (if found) using binary search!!! Please enter the number of elements in the LIST: 5 Enter the element of the LIST in ascending order: 12 23 34 45 56 Element to be searched: 33 Entered elements in the LIST are: 12 23 34 45 56 The searched item 33 is not found in the LIST. (E) Analysis of Binary Search Method : Each step of the algorithm divides the block of items being searched in half. We can divide a set of

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

n items in half at most log2 n times. Thus the running time of a binary search is proportional to log n and we say this is a O(log n) algorithm. (F) Comparison Between Sequential and Binary Search : Binary search requires a more complex program than our sequential search and thus for small n it may run slower than the sequential search. However, for large n, lim log n =0 n->∞ n
232 Data Structures

Thus at large n, log n is much smaller than n, consequently an O(log n) algorithm is much faster than an O(n) one.

n f(n)

log(n)

n
Fig. 3.27 Plot of n and log n vs n

3.12 HEIGHT BALANCED TREE
A height-balanced tree is a binary tree that has equal depth throughout the tree, +/- one level, i.e., heights do not differ from greater than one. In figure 3.28(a), the left sub-tree of the tree has a depth of three, while the right sub-tree has a depth of two, so they are balanced, since their heights do not differ by greater than one. However, in figure 3.28(b), the left sub-tree of the tree has a depth of three, while the right sub-tree has a depth of one, so it is not a balanced tree, since their heights differ by greater than one.
F

DEPTH 1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

C

J

DEPTH 2

B

D

DEPTH 3

Fig. 3.28(a) Height Balanced Tree Trees 233 F

DEPTH 1

C

DEPTH 2

B Fig. 3.28(b) Height Unbalanced Tree

DEPTH 3

Height balanced trees are used in order to maximise the efficiency of the operations on a tree. An unbalanced tree which, in the worst case operates like a linked list (complexity of linked list search is O(N). By balancing the tree the worst case complexity can be reduced to O(Log N).

3.13 WEIGHT BALANCED TREE
The nodes of a weight-balanced tree contain a data element, a left and right pointer, and a probability or weight field. The data element and left and right pointers are essentially the same as any other node. The probability field is a special addition for a weight-balanced tree. This field holds the probability of the node being accessed again. There are many different ways of coming up with this number. A good example of such a metric is the computing the probability according to the number of times the node has been previously searched for.
A ⋅9

B ⋅7

C ⋅5

D ⋅2 Fig.3.29 A Weight Balanced Tree

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

When the tree is set up, the nodes with the highest probability of access are placed at the top. That way the nodes that are most likely to be accessed have the lowest search time. The tree is balanced, if the weights in the right and left sub trees are as equal as possible. The average length of a search in a weighted tree is equal to the sum of: probability * depth for every node in the tree The tree is set up with the highest weighted node at the top of the tree or sub-tree. The left sub-tree contains nodes whose data values
234 Data Structures

are less than the current node, and the right sub-tree contains nodes that have data values greater than the current data value.

3.14 MULTIWAY SEARCH TREES
Each internal node v of a multi-way search tree T has at least two children, contains d-1 items, where d is the number of children of v. An item is of the form (ki ,xi ) for 1 ≤ i ≤ d-1, where ki is a key such that ki≤ki+1 for 1≤ i<d-1, xi is an element that contains two pseudo-items k0 = - ∞ and kd =+∞. k0 k1….. ki-1 ki ……kd
Fig. 3.30(a)

Children of each internal node are "between" the items in that node. If Ti is the sub-tree rooted at child vi, then all keys in Ti fall between the keys ki-1 and ki, that is, ki-1≤Ti≤ki. k0 k1 … ki-1 ki … kd-1
T1

kd
Td

Ti

Fig. 3.30(b)

A multi way search tree T storing n items has n+1 external nodes.

3.15 DIGITAL SEARCH TREES
A digital search tree is a binary tree where each node has one element. All nodes in the left sub-tree of a node at level i (root at level 0, its children at level 1, etc.) have an ith bit of 0. Similarly, all nodes in the right sub-tree of a node at level i have an ith bit of 1. Since we assume no duplicate keys. Hence, tree can have height at most log k, the number of bits in our keys. The search method looks like this : void digital_search (Tree t, Key k) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

…… digital_search_sub(t.root, k, 0); …… } digital_search_sub(Node n, Key k, int b) { if (n==null) printf(“not there\n”); if (k == n.key)
Trees 235

return n.val; if (digit(k,b) == 0) return digital_search_sub(n.left, k, b+1); else return digital_search_sub(n.right, k, b+1); } Insert follows the same descent strategy and puts the new node where the first null is reached. Delete can find the element, delete it, and recursively move children into their parent's position until every node again has an element. Digital search trees are not sorted. So, we do not have to replace the element with its successor. In fact, despite efficient insert, lookup, and delete, digital search trees do not have efficient predecessor and successor.

3.16 HASHING
It is a searching technique, which is independent of the number n of elements in the collection of data. 3.16.1 Hash Table : The hash table contains key values with pointers to the corresponding records. The basic idea of a hash table is that we have to place a key value into a location in the hash table, the location will be calculated from the key value itself. This one-one mapping between a key value and index in the hash table is known as hashing. 3.16.2 Hashing Function : The general idea of using the key to determine the address of a record is an excellent idea, but it must be modified so that a great deal of space in not wasted. This modification takes the form of a function H from the set K of keys into the set L of memory addresses, i.e., H: K → L This function is called the hash function. The two principal criteria for selecting a hash function H: K→ L are : (a) The function H should be easy and quick to compute.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(b) The function H should distribute the elements of our collection as uniformly as possible to the L slots of the hash table. The key criterion is that there should be a minimum number of collisions. Following are the some popular hash functions, which can be used in many applications : (i) The Division Method : One of the most widely accepted hashing function is the division method, which is defined as follows : Select a number m larger than the number n of keys in K. The hash function H is defined as : H(k) = k(mod m) or H(k) = k(mod m) +1
236 Data Structures

The first formula is used when the hash addresses range from 0 to m-1, otherwise 1 to m. Where k∈K, a key value. The operator mod denotes the module arithmetic, which is equal to the remainder of dividing k by m. Let us take an example, if m=13 and k=32 then, H(34) = 32(mod 13) = 6 or H(34) = 32(mod 13) +1 = 7 When using this method, we usually avoid certain values of m. Powers of 2 are usually avoided, for k mod 2b simply selects the b low order bits of k. Unless we know that all the 2b possible values of the lower order bits are equally likely, this will not be a good choice, because some bits of the key are not used in the hash function. Prime numbers, which are close to powers of 2, seem to be generally good choices for m. For example, if we have 4000 elements, and we have chosen an overflow table organisation, but wish to have the probability of collisions quite low, then we might choose m = 4093(4093 is the largest prime less than 4096 = 212). (ii) Midsquare Method : In this method, a key is multiplied by itself and the address is calculated by selecting an appropriate number of bits or digits from the middle of the number. This selection usually depends on the size of the hash table. The function is defined as : H(k) = m Where m is obtained by deleting digits or bits from both ends of k2. Let us take an example, consider a key value of four digits of integer type and we require a hash addresses of 3 digits. k: 1234 k2 : 1522756 H(k) : 227 This method gives a good results when applied to certain keys sets but is criticised because of time consuming multiplication operation.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

(iii) Folding Method : In this method, key k is partitioned into number of parts, k1, k2, … kn, where each of which has the same number of digits as the required address except possible the last part kn. The parts are added together, ignoring the final carry, to form an address. That is : H(k) = k1+ k2+….. + kn There are various variations in this method. In fold shifting method, the even number parts k2, k4, …are reversed and added. In fold shifting method the boundary parts k1, kn are reversed before they are added to the other parts. Let us take an example in which the size of the each part of the key is 3.
Trees 237

k: 356942781 parts : k1 = 356 k2 = 942 k3 = 781 Fold Shifting : k1 = 356 k2 = 249 k3 = 781 356+249+781 =1386 Fold Boundary : k1 = 653 k2 = 942 k3 = 187 653+942+187 = 1782 This method is also useful in converting multiword keys into a single word so that it can be used by the other hashing function. 3.16.3 Collisions Resolution Techniques: In the small number of cases, where multiple keys map to the same hash address, then elements with different keys may be stored in the same "slot" of the hash table. This situation is called the collision. Various techniques are used to resolve the collisions : (i) Linear Probing : In linear probing, when a collision occurs, the new element is put in the next available spot (by doing a sequential search). For example, Insert : 49 18 89 48, Hash table size = 10, so 49 % 10 = 9, 18 % 10 = 8, 89 % 10 = 9, 48 % 10 = 8 Table 3.4
Insert 1 Insert 2 Insert 3 Insert 4

[0] [1] [2] [3] [4]

89

89 48

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

[5] [6] [7] [8] 18 18 18 [9] 49 49 49 49 The problem with linear probing is that records tend to get clustered around each other i.e., once an element is placed in the hash table the chances of it’s adjacent element being filled are doubled (i.e., it can either be filled by a collision or directly). If two adjacent elements are filled then the chances of the next element being filled is three times that for an element with no neighbour.
238 Data Structures

(ii) Quadratic Probing : Quadratic probing is a collision resolution method that eliminates the primary clustering problem of linear probing. In quadratic probing, if there is a collision we first try and insert an element in the next adjacent space (at a distance of +1). If this is full we try a distance of 4 (22) then 9 (32) and so until we find an empty element. The full index function is of the form : (h + i2) % HashTableSize for i = 0,1,2,3,... Where h is the initial hashed key value. We take the modulus of the result so the search can wrap around to the beginning of the table. Even so not all the locations in a table may be able to be reached (especially if the table size is a power of 2). This means we may not be able to insert a value even though the table is not full. Generally though, in linear and quadratic probing, the hash table size is deliberately kept considerably larger than the number of expected keys, otherwise the performance of hashing becomes too slow (as the table becomes fuller more collisions occur and more probing is required to insert and retrieve elements). For example, As before insert : 49 18 89 48, Hash table size = 10 Table 3.5
Insert 1 Insert 2 Insert 3 Insert 4

[0] [1] [2] [3] [4] [5] [6]

89

89 48

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

[7] [8] 18 18 18 [9] 49 49 49 49 (iii) Double Hashing : Another method of probing is to use a second hash function to calculate the probing distance. For example, we define a second hash function Hash2(Key) and we use the return value as the probe value. If this results in a collision we try a distance of 2 * Hash2(Key), then 3 * Hash2(Key) and so on. A common second hash function is : Hash2(Key) = R - (Key % R) Where R is a prime number smaller than the hash table size. The full index function is then of the form :
Trees 239

(h + i*(R - (Key % R)) % HashTableSize for i = 0,1,2,3,... Where h is the initial hashed key value. (iv) Rehashing : If the table gets too full, the running time for the operations will start taking too long and inserts might fail with quadratic probing. The standard solution in this case is to build an entirely new hash table approximately twice the size of the original, calculate a new hash value for each key and then insert all keys into the new table (then destroying the old table). This is known as reorganisation or rehashing. (v) Chaining : In this method, we keep a linked list of all elements that hash to the same value. The hash table itself becomes an array of pointers to list nodes instead of an array of elements that hold actual records. When collisions occur in chaining, elements are simply added to the appropriate linked list. For example, Insert : 0 1 4 9 16 25 36 49 64 81, Hash table size = 10, so Table 3.6 [0] [1] [2] [3] [4] [5] [6] [7] [8] => => NULL NULL => => => NULL NULL 0 1 NULL => 81 NULL

4 25 16

=> NULL =>

64 36

NULL NULL

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

[9] => 9 => 49 NULL 3.16.4 Implementation of a Chained Hash Table : The following program hash_chained.c shows the implementation of chaining with keys taken from set of values from the int data type : /* hash_chained.c*/ #include <stdio.h> #include <stdlib.h> #define HTABLESIZE 10 struct Node { struct Node *Next; int Data; };
240 Data Structures

struct Node *HashTable[HTABLESIZE]; void HashTableCreate(); void HashTableDestroy(); int HashTableInsert(int); // =-1 on failure, =0 if ok struct Node *HashTableFind(int); // search return data node int HashTableDelete(int); // =0 on ok, =-1 on fail int HashFunction(int); void HashTablePrint(); // Print all elements in table void main() { int i; HashTableCreate(); for(i=1;i<200;++i) // Insert values from 1 -199 { HashTableInsert(i); } HashTablePrint(); // Print out all of the Hash Table for(i=50;i<=90;++i) // Remove keys 50-90 { HashTableDelete(i); } HashTablePrint(); // Print out Hash table HashTableDestroy(); // Destroy the Hash Table } void HashTableCreate() { int i; for(i=0;i<HTABLESIZE;++i)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

{ HashTable[i]=0; } } void HashTableDestroy() { int i; struct Node *p,*temp; for(i=0;i<HTABLESIZE;++i) { for(p=HashTable[i];p!=0; ) { temp=p;
Trees 241

p=p->Next; free(temp); } } } int HashTableInsert(int data) // =-1 on failure, =0 if ok { int ind; struct Node *nw; nw=(struct Node *)malloc(sizeof(struct Node)); if(nw==0) { return -1; } nw->Data=data; ind=HashFunction(data); nw->Next=HashTable[ind]; HashTable[ind]=nw; return 0; } struct Node *HashTableFind(int data) // search return data node { struct Node *p; for(p=HashTable[HashFunction(data)];p!=0;p=p->Next) { if(p->Data==data) { return p;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

} } return 0; } int HashTableDelete(int data) // =0 ok, =-1 on fail { int ind; struct Node *p,*temp; ind=HashFunction(data); if((p=HashTable[ind])==0) { return -1; }
242 Data Structures

if(p->Data==data) { HashTable[ind]=p->Next; free(p); return 0; } for( ; p->Next!=0 ; p=p->Next) { if(p->Next->Data==data) { temp=p->Next; p->Next=temp->Next; free(temp); return 0; } } return -1; } int HashFunction(int data) { return data%HTABLESIZE; // Simple Function } void HashTablePrint() // Print all elements in table { int i; for(i=0;i<HTABLESIZE;++i) { struct Node *p; printf("Slot %d:",i); for(p=HashTable[i];p!=0;p=p->Next)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

{ printf(" %d",p->Data); } printf("\n"); } printf("\n"); }

EXERCISE
Q.1. What is the purpose of writing the more complicated code to do binary searches, when a linear one will not only find the item if it is there, but does not even require the data to be sorted in the first place? Q.2. On your system, for what list length is a binary search more time efficient than a linear search?
Trees 243

Q.3. Write an algorithm to display the elements of a binary tree in level order,i.e., list the element in the root, followed by the elements in depth 1, then the elements at depth 2, and so on. Q.4. An in order threaded binary tree is given. Write an algorithm to find the pre order and post order threaded binary tree. Q.5. Suppose the following sequence list the nodes of a binary tree T in preorder and inorder, respectively : Preorder : G B Q A C K F P D E R H Inorder : Q B K C F A G P E D H R Draw the diagram of the tree. Q.6. Suppose the following eight numbers are inserted in order into an empty binary search tree T : 50 33 44 22 77 35 60 40 Draw the tree T. Q.7. Draw the binary expression for the following expression : E = (3x-y)(5a+b)4 Q.8. Write a function that counts number of nodes in a binary tree. Q.9. Draw the binary search tree whose elements are inserted in the following order : 50 72 96 107 26 12 11 9 2 10 25 51 16 17 95 Q.10. Write a program, which uses the mid square method to find the 2digit hash address of a 4-digit employee number key. Q.11. Draw all fourteen binary trees with four nodes. Q.12. Give the pre order, inorder, post order, and level-order traversals for the following trees :
C

O

U

S

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

N

R

L

O

G

A

T

A

T

N

I

244 Data Structures

Q.13. Give the pre order, inorder, post order, and level-order traversals for the following trees :
F

S

C

S

O

F

T

Q

H

M

D

I

L

?

E

I

U

R

Q.14. Draw the expression tree for the following expressions. Evaluate the tree by evaluating one level at each step. (a) (3+6)*(5%2) (b) ((((8-1)-2)-3)*3)+1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,   Pt. Ravishankar Shukla University,Raipur

2010 

**

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

4
4.1 INTRODUCTION

SORTING ALGORITHMS

This chapter covers various sorting techniques like- bubble sort, insertion sort, selection sort, quick sort, merge sort, address calculation sort and heap sort. These techniques are discussed with the help of array of integers. Complexity of the algorithm is also discussed at the end of the unit. An exercise at the end of chapter is given.

4.2 SORTING
Sorting is one of the most important operations performed by computers. In the days of magnetic tape storage before modern data-bases, it was almost certainly the most common operation performed by computers as most "database" updating was done by sorting transactions and merging them with a master file. It's still important for presentation of data extracted from databases: most people prefer to get reports sorted into some relevant order before wading through pages of data. The basic premise behind sorting an array is that, its elements start out in some (presumably) random order and need to be arranged from lowest to highest. If the number of items to be sorted is small, a reader may be able to tell at a glance what the correct order ought to be. If there are a large number of items, a more systematic approach is required. To do this, it is necessary to think about what it means for an array to be sorted. It is easy to see that the list 1, 5, 6, 19, 23, 45, 67, 98, 124, 401 is sorted, whereas the list 4, 1, 90, 34, 100, 45, 23, 82, 11, 0, 600, 345 is not. The property that makes the second one "not sorted" is that, there are adjacent elements that are out of order. The first item is greater than the second instead of less, and likewise the third is greater than the fourth and so on. Once this observation is made, it is not very hard to devise a sort that precedes by examining adjacent elements to see if they are in order, and swapping them if they are not. The following are the methods, which can be used for performing sorting : (i) bubble sort, (ii) selection sort, (iii) insertion sort, (iv) quick sort, (v) merge sort, (vi) address calculation sort, (vii) heap sort.
(245)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

246 Data Structures

4.2.1 Bubble Sort : In this sorting algorithm, multiple swapping takes place in one pass. Smaller elements move or 'bubble' up to the top of the list, hence the name bubble is given to the algorithm. This most elementary sorting method proceeds by scanning through the elements one pair at a time, and swapping any adjacent pairs it finds to be out of order. Thus, for the list in the example given below, the first two items are swapped, then the (new) second item is compared to the third (and not swapped,) the third is compared to the fourth, and so on to the end. The list would be altered as follows (comparisons are emphasized) : 4, 1, 90, 34, 100, 45, 23, 82, 11, 0, 600, 345 1, 4, 90, 34, 100, 45, 23, 82, 11, 0, 600, 345 1, 4, 90, 34, 100, 45, 23, 82, 11, 0, 600, 345 1, 4, 34, 90, 100, 45, 23, 82, 11, 0, 600, 345 1, 4, 34, 90, 100, 45, 23, 82, 11, 0, 600, 345 1, 4, 34, 90, 45, 100, 23, 82, 11, 0, 600, 345 1, 4, 34, 90, 45, 23, 100, 82, 11, 0, 600, 345 1, 4, 34, 90, 45, 23, 82, 100, 11, 0, 600, 345 1, 4, 34, 90, 45, 23, 82, 11, 100, 0, 600, 345 1, 4, 34, 90, 45, 23, 82, 11, 0, 100, 600, 345 1, 4, 34, 90, 45, 23, 82, 11, 0, 100, 600, 345 1, 4, 34, 90, 45, 23, 82, 11, 0, 100, 345, 600 Unfortunately, the list is not yet sorted, as there are still several places where adjacent items are out of order. The number 0, for instance, which should be in first slot, is in the ninth slot. Notice, however, that the largest item worked its way to the top position, and indeed, this algorithm will always force this to happen. Thus, if at this point the same strategy is continued, it is only the first n-1 items that need to be scanned. On the second pass, the second largest item will move to its correct position, and on the third pass (stopping at item n-3) the third largest item will be in place. It is this gradual percolation, or bubbling of the larger items to the top end that gives this sorting technique its name. There are two ways in which the sort can terminate with everything in the right order. It could complete by reaching the n-1th pass and placing the second smallest item in its correct position. Alternately, it could find on some earlier pass that nothing needs to be swapped. That is, all adjacent pairs are already in the correct order. In this case, there is no need to go on to subsequent passes, for the sort is complete already.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 247

If the list started in sorted order, this would happen on the very first pass. If it started in reverse order, it would not happen until the last one. When this sort was tested, statements were included to print the array after each comparison, and to print the number of swaps on each pass. The original data is given first, and the items that are compared are emphasized. 234 77 0 113 404 94 900 113 15 300 13 135 Pass number 1 77 234 0 113 404 94 900 113 15 300 13 135 77 0 234 113 404 94 900 113 15 300 13 135 77 0 113 234 404 94 900 113 15 300 13 135 77 0 113 234 404 94 900 113 15 300 13 135 77 0 113 234 94 404 900 113 15 300 13 135 77 0 113 234 94 404 900 113 15 300 13 135 77 0 113 234 94 404 113 900 15 300 13 135 77 0 113 234 94 404 113 15 900 300 13 135 77 0 113 234 94 404 113 15 300 900 13 135 77 0 113 234 94 404 113 15 300 13 900 135 77 0 113 234 94 404 113 15 300 13 135 900 Swaps on this pass = 9 Pass number 2 0 77 113 234 94 404 113 15 300 13 135 900 0 77 113 234 94 404 113 15 300 13 135 900 0 77 113 234 94 404 113 15 300 13 135 900 0 77 113 94 234 404 113 15 300 13 135 900 0 77 113 94 234 404 113 15 300 13 135 900 0 77 113 94 234 113 404 15 300 13 135 900 0 77 113 94 234 113 15 404 300 13 135 900 0 77 113 94 234 113 15 300 404 13 135 900 0 77 113 94 234 113 15 300 13 404 135 900 0 77 113 94 234 113 15 300 13 135 404 900 Swaps on this pass = 7 Pass number 3 0 77 113 94 234 113 15 300 13 135 404 900 0 77 113 94 234 113 15 300 13 135 404 900 0 77 94 113 234 113 15 300 13 135 404 900 0 77 94 113 234 113 15 300 13 135 404 900 0 77 94 113 113 234 15 300 13 135 404 900 0 77 94 113 113 15 234 300 13 135 404 900 0 77 94 113 113 15 234 300 13 135 404 900 0 77 94 113 113 15 234 13 300 135 404 900 0 77 94 113 113 15 234 13 135 300 404 900 Swaps on this pass = 5

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

248 Data Structures

Pass number 4 0 77 94 113 113 15 234 13 0 77 94 113 113 15 234 13 0 77 94 113 113 15 234 13 0 77 94 113 113 15 234 13 0 77 94 113 15 113 234 13 0 77 94 113 15 113 234 13 0 77 94 113 15 113 13 234 0 77 94 113 15 113 13 135 Swaps on this pass = 3 Pass number 5 0 77 94 113 15 113 13 135 0 77 94 113 15 113 13 135 0 77 94 113 15 113 13 135 0 77 94 15 113 113 13 135 0 77 94 15 113 113 13 135 0 77 94 15 113 13 113 135 0 77 94 15 113 13 113 135 Swaps on this pass = 2 Pass number 6 0 77 94 15 113 13 113 135 0 77 94 15 113 13 113 135 0 77 15 94 113 13 113 135 0 77 15 94 113 13 113 135 0 77 15 94 13 113 113 135 0 77 15 94 13 113 113 135 Swaps on this pass = 2 Pass number 7 0 77 15 94 13 113 113 135 0 15 77 94 13 113 113 135 0 15 77 94 13 113 113 135 0 15 77 13 94 113 113 135 0 15 77 13 94 113 113 135 Swaps on this pass = 2 Pass number 8 0 15 77 13 94 113 113 135 0 15 77 13 94 113 113 135 0 15 13 77 94 113 113 135 0 15 13 77 94 113 113 135 Swaps on this pass = 1

135 135 135 135 135 135 135 234

300 300 300 300 300 300 300 300

404 404 404 404 404 404 404 404

900 900 900 900 900 900 900 900

234 234 234 234 234 234 234

300 300 300 300 300 300 300

404 404 404 404 404 404 404

900 900 900 900 900 900 900

234 234 234 234 234 234

300 300 300 300 300 300

404 404 404 404 404 404

900 900 900 900 900 900

234 234 234 234 234

300 300 300 300 300

404 404 404 404 404

900 900 900 900 900

234 234 234 234

300 300 300 300

404 404 404 404

900 900 900 900

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 249

Pass number 9 0 15 13 77 94 113 113 135 234 300 404 900 0 13 15 77 94 113 113 135 234 300 404 900 0 13 15 77 94 113 113 135 234 300 404 900 Swaps on this pass = 1 Pass number 10 0 13 15 77 94 113 113 135 234 300 404 900 0 13 15 77 94 113 113 135 234 300 404 900 Swaps on this pass = 0 (A) Algorithm : The steps to be taken are as follows : (a) Initialise k = n-1 (b) Repeat steps (c) to (f) while(k>0) (c) Initialise i = 0 (d) Repeat steps (e) to (f) while(i<k) (e) [Compare the i’th element to the i+1’th element] If(array[i] > array[i+1]) then (f) Set temp = array[i] array[i] = array[i+1] array[i+1] = temp (g) End. (B) Equivalent C Function void BubbleSort(int array[],int n) { int i,k,temp; for(k=n-1;k>0;k- -) { for(i=0;i<k;++i) { if(array[i]>array[i+1]) { temp=array[i]; array[i]=array[i+1]; array[i+1]=temp; } } } } (C) Implementation of Bubble Sort Function : The following program sort_bubble.c implements the bubble sort function using the array of integers : /*sort_bubble.c*/ #include <stdio.h> #include <stdlib.h>

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

250 Data Structures

#define N 100 void Input(int array[],int n); void BubbleSort(int array[],int n); void Print(int array[],int n); void main() { int n,array[N]; printf("!!!This program sorts the array of integers using bubble sort algorithm!!!\n"); printf("Please enter how many numbers are there in the array:\n"); scanf("%d",&n); Input(array,n); BubbleSort(array,n); Print(array,n); } // BUBBLE SORT //////////////// void BubbleSort(int array[],int n) { int i,k,temp; for(k=n-1;k>0;k--) { for(i=0;i<k;++i) { if(array[i]>array[i+1]) { temp=array[i]; array[i]=array[i+1]; array[i+1]=temp; } } } } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("Array before sorting: "); for(i=0;i<n;++i) printf("%d ",array[i]); printf("\n"); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 251

void Print(int array[],int n) { int i; printf("Array after sorting: "); for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); } (D) Output of the Program !!!This program sorts the array of integers using bubble sort algorithm!!! Please enter how many numbers are there in the array : 10 Please enter the number of the array : 12 21 32 31 45 34 56 54 67 65 Array before sorting: 12 21 32 31 45 34 56 54 67 65 Array after sorting: 12 21 31 32 34 45 54 56 65 67 (E) Analysis : The best case involves performing one pass, which requires n-1 comparisons in the outer loop. Hence, the best case is O(n). In worst case, array is in reverse order and the inner loop uses the maximum number of comparisons n-1. Hence, the worst case is O(n2). The average case is more difficult to analyse. The number of comparisons in the inner loop is (n-1)/2. Hence, the average case is O(n2). 4.2.2 Selection Sort : It is not difficult to see that some additional efficiency can be obtained for the bubble sort. It uses many swaps to get the largest item into its correct position on each pass, and some of these are wasted. If the scan is modified so that it simply finds the smallest item in the range being scanned and no interchanges are done until the scan is finished, all the intermediate swaps can be eliminated. Then, when the pass is complete, the smallest item can be swapped it with the first item in the array. For instance, starting with the list :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

252 Data Structures

234 77 0 113 404 94 900 115 15 300 13 135 one would find the number 0 to be the smallest on the first pass (as with the bubble sort,) but do only the swap from its present position to the first spot for the pass. This process is called selection sort. Successive passes would produce the lists : Pass number 1 0 77 234 113 404 94 900 115 15 300 13 135 Pass number 2 0 13 234 113 404 94 900 115 15 300 77 135 Pass number 3 0 13 15 113 404 94 900 115 234 300 77 135 Pass number 4 0 13 15 77 404 94 900 115 234 300 113 135 Pass number 5 0 13 15 77 94 404 900 115 234 300 113 135 Pass number 6 0 13 15 77 94 113 900 115 234 300 404 135 Pass number 7 0 13 15 77 94 113 115 900 234 300 404 135 Pass number 8 0 13 15 77 94 113 115 135 234 300 404 900 Pass number 9 0 13 15 77 94 113 115 135 234 300 404 900 Pass number 10 0 13 15 77 94 113 115 135 234 300 404 900 Pass number 11 0 13 15 77 94 113 115 135 234 300 404 900 (A) Algorithm : The steps to be taken are as follows : (a) Initialise k = n-1 (b) Repeat steps (c) to (g) while(k>0) (c) Initialise pos = 0, i = 1 (d) Repeat steps (e) to (f) while(i<=k) (e) [Compare the i’th element to the pos element] If(array[i] > array[pos]) then (f) Set pos = i (g) Set temp=array[pos]; array[pos]=array[k]; array[k]=temp; (h) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 253

(B) Equivalent C Function void SelectionSort(int array[],int n) { int i,k,pos,min,temp; for(k=0;k<n;k++) { min = array[k]; pos=k; for(i=k+1;i<n;++i) { if(array[i]<min) { min = array[i]; pos=i; } } temp=array[k]; array[k]=array[pos]; array[pos]=temp; } } (C) Implementation of Selection Sort Function : The following program sort_selection.c implements the selection sort function using the array of integers : /*sort_selection.c */ #include <stdio.h> #include <stdlib.h> #define N 100 void Input(int array[],int n); void SelectionSort(int array[],int n); void Print(int array[],int n); void main() { int n,array[N]; printf("!!!This program sorts the array of integers using selection sort algorithm!!!\n"); printf("Please enter how many numbers are there in the array:\n"); scanf("%d",&n); Input(array,n); SelectionSort(array,n); Print(array,n); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

254 Data Structures

void SelectionSort(int array[],int n) { int i,k,pos,min,temp; for(k=0;k<n;k++) { min = array[k]; pos=k; for(i=k+1;i<n;++i) { if(array[i]<min) { min = array[i]; //Find the smallest value pos=i; } } temp=array[k]; array[k]=array[pos]; array[pos]=temp; } } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("Array before sorting: "); for(i=0;i<n;++i) printf("%d ",array[i]); printf("\n"); } void Print(int array[],int n) { int i; printf("Array after sorting: "); for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); } (D) Output of the Program !!!This program sorts the array of integers using selection sort algorithm!!!

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 255

Please enter how many numbers are there in the array: 12 Please enter the number of the array: 234 77 113 404 94 900 113 15 300 13 135 5 Array before sorting: 234 77 113 404 94 900 113 15 300 13 135 5 Array after sorting: 5 13 15 77 94 113 113 135 234 300 404 900 (E) Analysis : During the first pass, in which the record with the smallest key is found, n-1 records are compared. In general for i’th pass of the sort, n-i comparisons are required. The total number of comparisons is therefore, n(n-1)/2. Hence, the number of comparisons is proportional to O(n2). 4.2.3 Insertion Sort : An insertion sort works by growing a sorted group. The group starts with a single element, and a new element is continuously added by shifting each member of the group until the position where the new element is added. The following example demonstrates an insertion sort on an array of integers : 113 77 0 50 113 114 900 113 15 300 13 135 1 77 113 0 50 113 114 900 113 15 300 13 135 1 0 77 113 50 113 114 900 113 15 300 13 135 1 0 50 77 113 113 114 900 113 15 300 13 135 1 0 50 77 113 113 114 900 113 15 300 13 135 1 0 50 77 113 113 114 900 113 15 300 13 135 1 0 50 77 113 113 114 900 113 15 300 13 135 1 0 50 77 113 113 113 114 900 15 300 13 135 1 0 15 50 77 113 113 113 114 900 300 13 135 1 0 15 50 77 113 113 113 114 300 900 13 135 1 0 13 15 50 77 113 113 113 114 300 900 135 1 0 13 15 50 77 113 113 113 114 135 300 900 1 0 1 13 15 50 77 113 113 113 114 135 300 900

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

256 Data Structures

(A) Algorithm : The steps to be taken are as follows : (a) Initialise k = 1 (b) Repeat steps (c) to (g) while(k<n) (c) Set element = array[k] (d) Initialise pos = k-1 (e) Repeat steps (f) while(array[pos]>element && pos>=0) (f) Set array[pos+1] = array[pos] (g) Set array[pos+1] = element (h) End. (B) Equivalent C Function void InsertionSort(int array[],int n) { int k ,element, pos; for(k=1;k<n;++k) { element=array[k]; for(pos=k-1;array[pos]>element && pos>=0;pos--) { array[pos+1]=array[pos]; } array[pos+1]=element; } } (C) Implementation of Insertion Sort Function : The following program sort_insertion.c implements the insertion sort function using the array of integers : /* sort_insertion.c */ #include <stdio.h> #include <stdlib.h> #define N 100 void Input(int array[],int n); void InsertionSort(int array[],int n); void Print(int array[],int n); void main() { int n,array[N]; printf("!!!This program sorts the array of integers using insertion sort algorithm!!!\n"); printf("Please enter how many numbers are there in the array:\n"); scanf("%d",&n); Input(array,n);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 257

InsertionSort(array,n); Print(array,n); } // INSERTION SORT //////////////// void InsertionSort(int array[],int n) { int k ,element, pos; for(k=1;k<n;++k) { element=array[k]; for(pos=k-1;array[pos]>element && pos>=0;pos--) { array[pos+1]=array[pos]; } array[pos+1]=element; } } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("Array before sorting: "); for(i=0;i<n;++i) printf("%d ",array[i]); printf("\n"); } void Print(int array[],int n) { int i; printf("Array after sorting: "); for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); } (D) Output of the Program !!!This program sorts the array of integers using insertion sort algorithm!!! Please enter how many numbers are there in the array: 12

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

258 Data Structures

Please enter the number of the array: 113 77 50 113 114 900 113 15 300 13 135 1 Array before sorting: 113 77 50 113 114 900 113 15 300 13 135 1 Array after sorting: 1 13 15 50 77 113 113 113 114 135 300 900 Analysis : This sorting method is frequently used when the array size is small and linear search is about as efficient as the binary search. The best case requires array to be in order, so that it involves performing only one pass, which requires n-1 comparisons in the outer loop. Hence, the best case is O(n). The worst case is there, if array is in reverse order and the inner loop uses the maximum number of comparisons n-1. Hence, the worst case is O(n2). The average case is more difficult to analyse. The number of comparisons in the inner loop is (n-1)/2. Hence, the average case is O(n2). 4.2.4 Quick Sort : The method of sorting by partitioning a list into two sub-lists around some pivot, (where the items in the left sub-list are all less than the pivot, and those in the right sub-list are all greater than the pivot), and then recursively sorting the left and right sub-lists in the same manner is called a quick sort. The key to realising steps two and three in the sequence above is to start with the next item after the pivot, and counting forward, discover the first one that is greater than the pivot(i.e., it really belongs to the right sub-list). One then commences examining items from the last in the current list backwards to find the first one that is less than the pivot (i.e., it really belongs to the left sub-list). Since these two items are both now in the wrong sub-list, swap them. Then pick up the count again where it left off and continue, gradually working towards a collision between the two counters. To see this in operation, suppose one begins with the list :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 259

16 7 9 44 2 18 8 53 1 5 17 Isolating item #1 (16) as the pivot, scan from #2 and discover that item #4 (44) is the first one greater than 16. Suspending the count here, begin with item #11 (17) and work backwards. Item #10 (5) is the first one less than 16, so swap it with item #4 to get : 7 9 5 2 18 8 53 1 44 17 16 The underscore marks the two that were swapped and also the places where counting was suspended in the forward and backward scans. Continuing, the next two that must be swapped because they are in the wrong sub-list are item #6 (18) and item #9 (1) so the list becomes: 7 9 5 2 1 8 53 18 44 17 16 The next item found that is greater than 16 is item #8 (53), but at this point, the count from the right passes with the one from the left (at the arrow) without finding another item less than the pivot value. So, there are no more swaps to make in this pass, and the scan has now found the correct place to put the pivot item (at position #7) : 7 9 5 2 1 8 53 18 44 17 16 Rather than move everything down and insert it there, observe that the lower items are out of order any way and can be re-positioned later, so it will do to simply swap the pivot item with item #7. This produces: 16 53 18 44 17 8 7 9 5 2 1 The list is written with the 16 isolated, inverted and separating two sub-lists so as to emphasize the fact of the partition. The item 16 is now in the correct position and should never be touched again. Because of the way in which the correct position for the item 16 was located, everything in the left sub-list is now less than 16, and everything in the right sub-list is greater than 16 (hence the name pivot). Thinking recursively, it is now possible to observe that when the left and right sublists are sorted, the entire list will be sorted. Repeating for the left sub-list yields : 9 5 2 1 16 53 18 44 17 8 7 1 5 2 9 16 53 18 44 17 8 7

8 9 16 53 2 7 1 5 Repeat for the left sub-list of the 8, to obtain : 1 5 8 9 16 53 2 7 2 1 7 5 8 9 16 53

18 18 18

44 44 44

17 17 17

1

2

7

5

8

9

16

53

18

44

17

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

260 Data Structures

The left sub-list of the pivot 2 is sorted. When the right sub-list of pivot 2 (two items) is sorted, one has : 1 2 5 7 8 9 16 53 18 44 17 Now, the left sub-list of the last pivot (7) has only one item and it is sorted. Backing up the recursion chain, the right sub-list of the pivot 8 also has only one item (9), it is already sorted. Backing up further, the next list to sort is the right sub-list of the original pivot 16. 1 2 5 7 8 9 16 53 18 44 17

1 1

2 2

5 5

7 7

8 8

9 9

16 16

17 17

18 18

44 44

53 53

1

2

5

7

8

9

16

17

18

44

53

1 2 5 7 8 9 16 17 18 44 53 The last right sub-list of the pivot 18 has only one element and is sorted, so the entire sort is finished. Note that there were even places where one or the other of the two sub-lists was empty and also did not need to be considered. Having carefully hand-stepped through this sorting method, it is now possible to produce the code for the quick sort. This code will depart a little from the previous conventions for sorts in this chapter, in that, it will assume that it is being called by a client that is already numbering the array [0 .. n-1]. This assumption is made because the quick sort, being recursive, is its own major client, and already has the array numbered in that manner when it calls itself. Notice, also the treatment of numbers scanned in either direction that are equal to the pivot. They are left where they are for that scan. Eventually, they will be shuffled adjacent to this pivot when another sublist is sorted. (A) Algorithm : The array[] is an array with n elements. The method of sorting by partitioning a list into two sub-lists around some pivotpos, (where the items in the left sub-list are all less than the pivotpos, and those in the right sub-list are all greater than the pivotpos), and then recursively sorting the left and right sub-lists. Steps : The steps to be taken are as follows : (a) If n<=1 then return (b) [Otherwise call function partition] pivotpos = Partition(array,n)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 261

(c) [Recursively call the function quick sort for both partitions] QuickSort(array,pivotpos) QuickSort(array+pivotpos+1,n-pivotpos-1) (d) End. (B) Equivalent C Function void QuickSort(int array[],int n) { int pivotpos; if(n<=1) { return; } pivotpos=Partition(array,n); QuickSort(array,pivotpos); QuickSort(array+pivotpos+1,n-pivotpos-1); } int Partition(int array[],int n) { int pivot,left,right,swap; pivot=array[0]; // First element is pivot left=0; right=n-1; for( ; ; ) { while(left<right && array[left]<=pivot) { left++; } while(left<right && array[right]>pivot) { right--; } if(left==right) { if(array[right]>pivot) { left=left-1; } break; } swap=array[left]; array[left]=array[right]; array[right]=swap; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

262 Data Structures

swap=array[0]; array[0]=array[left]; array[left]=swap; return left; } (C) Implementation of Quick Sort Function : The following program sort_quick.c implements the quick sort function using the array of integers : /* sort_quick.c */ #include <stdio.h> #include <stdlib.h> #define N 100 void QuickSort(int array[],int n); // Quick Sort int Partition(int array[],int n); // returns index of pivot void Input(int array[],int n); void Print(int array[],int n); void main() { int n,array[N]; printf("!!!This program sorts the array of integers using quick sort algorithm!!!\n"); printf("Please enter how many number are there in the array:\n"); scanf("%d",&n); Input(array,n); QuickSort(array,n); Print(array,n); } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("array before sorting: "); for(i=0;i<n;++i) printf("%d ",array[i]); printf("\n"); } void Print(int array[],int n) { int i; printf("array after sorting: ");

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 263

for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); } void QuickSort(int array[],int n) { int pivotpos; if(n<=1) { return; } pivotpos=Partition(array,n); QuickSort(array,pivotpos); QuickSort(array+pivotpos+1,n-pivotpos-1); } int Partition(int array[],int n) { int pivot,left,right,swap; pivot=array[0]; // First element is pivot left=0; right=n-1; for( ; ; ) { while(left<right && array[left]<=pivot) { left++; } while(left<right && array[right]>pivot) { right--; } if(left==right) { if(array[right]>pivot) { left=left-1; } break; } swap=array[left]; array[left]=array[right]; array[right]=swap; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

264 Data Structures

swap=array[0]; array[0]=array[left]; array[left]=swap; return left; } (D) Output of the Program !!!This program sorts the array of integers using quick sort algorithm !!! Please enter how many numbers are there in the array: 12 Please enter the number of the array: 16 7 9 44 2 18 8 53 1 5 17 22 Array before sorting: 16 7 9 44 2 18 8 53 1 5 17 22 Array after sorting: 1 2 5 7 8 9 16 17 18 22 44 53 (E) Analysis : The best case analysis occurs when, the file is always partitioned in half. The analysis becomes O(n log n). The worst case occurs when, at each invocation of the function, the current list is partitioned into two sub-lists with one of them being empty or key element is smallest or largest one. The worst case analysis becomes O(n2). For the average case, analysis becomes O(n log n). 4.2.5 Merge Sort : The basic idea is that, if we know we have two sorted lists, we can combine them into a single large sorted list by just looking at the first item in each list. Whichever is smaller is moved to the single list being assembled. There is then a new first item in the list from which the item was moved, and the process repeats. The process overall is thus : (a) Split the original list into two halves. (b) Sort each half (using merge sort). (c) Merge the two sorted halves together into a single sorted list. Example : The following example performs a merge sort on an array of integers :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 265

34 56 78 12 45 3 99 23 34 56 78 12⏐ 45 3 99 23 34 56⏐ 78 12⏐ 45 3⏐ 99 23 34 ⏐56⏐ 78⏐12⏐ 45⏐ 3⏐ 99⏐ 23 34 56⏐ 12 78⏐ 3 45⏐ 23 99 12 34 56 78 ⏐3 23 45 99 3 12 23 34 45 56 78 99 (A) Algorithm : The steps to be taken for merge sort are as follows : (a) [Check the size of the array] If n=1 then return (b) [Otherwise check the first and last integer] If(first!=last)then repeat step (c) to (f) (c) [Find the middle integer] middle = ((last + first)/2) (d) [Recursively sort the left half array] MergeSort(array,first,middle) (e) [Recursively sort the right half array] MergeSort(array,middle+1,last) (f) [Merge two ordered sub-arrays] Merge(array,first,middle,last) (g) End. (B) Equivalent C Function void MergeSort(int array[],int i,int n) { int mid,first,last; first=i; last=n; if(first!=last) { mid = (first+last)/2; MergeSort(array,first,mid); MergeSort(array,mid+1,last); Merge(array,first,mid,last); } } void Merge(int array[],int first,int n,int last) { int temp[100]; int f = first; int w = n+1; int l = last; int upper;

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

266 Data Structures

while((f<=n)&&(w<=last)) { if(array[f]<=array[w]) { temp[l]=array[f]; f++; } else { temp[l]=array[w]; w++; } l++; } if(f<=n) { for(f=f;f<=n;f++) { temp[l] = array[f]; l++; } } else { for(w=w;w<=last;w++) { temp[l]=array[w]; l++; } } for(upper=first;upper<=last;upper++) // copy result back array[upper]=temp[upper]; } (C) Implementation of Merge Sort Function : The following program sort_merge.c implements the merge sort function using the array of integers : /* sort_merge.c */ #include <stdio.h> #include <stdlib.h> #define N 100 void Input(int array[],int n); void MergeSort(int array[],int i,int n);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 267

void Merge(int array[],int f, int l,int n); void Print(int array[],int n); void main() { int i=0,n,array[N]; printf("!!!This program sorts the array of integers using merge sort algorithm!!!\n"); printf("Please enter how many number are there in the array:\n"); scanf("%d",&n); input(array,n); MergeSort(array,i,n-1); Print(array,n); } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("Array before sorting: "); for(i=0;i<n;++i) printf("%d",array[i]); printf("\n"); } void Print(int array[],int n) { int i; printf("Array after sorting: "); for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); } void MergeSort(int array[],int i,int n) { int mid,first,last; first=i; last=n; if(first!=last) { mid = (first+last)/2; MergeSort(array,first,mid);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

268 Data Structures

MergeSort(array,mid+1,last); Merge(array,first,mid,last); } } void Merge(int array[],int first,int n,int last) { int temp[100]; int f = first; int w = n+1; int l = last; int upper; while((f<=n)&&(w<=last)) { if(array[f]<=array[w]) { temp[l]=array[f]; f++; } else { temp[l]=array[w]; w++; } l++; } if(f<=n) { for(f=f;f<=n;f++) { temp[l] = array[f]; l++; } } else { for(w=w;w<=last;w++) { temp[l]=array[w]; l++; } } for(upper=first;upper<=last;upper++) // copy result back array[upper]=temp[upper]; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 269

(D) Output of the Program !!!This program sorts the array of integers using merge sort algorithm!!! Please enter how many numbers are there in the array: 8 Please enter the number of the array: 34 56 78 12 45 3 99 23 Array before sorting: 34 56 78 12 45 3 99 23 Array after sorting: 3 12 23 34 45 56 78 99 (E) Analysis : In this method, since log n passes are required in the sort, the total number of comparisons required are O(n log n) in all three cases i.e., best case, average case and worst case. To execute the algorithm, extra space needed is equal to the number of elements in the list i.e., space complexity is O(n). One of the drawbacks of this method is the large auxiliary area required. 4.2.6 Address Calculation Sort : This method uses hash function for sorting. Depending on the result of the hash function the key is applied into the one of the linked lists. Each set of keys, which hash into the same address, is called as equivalence class. Each equivalence is represented by a linked list. In case, if there is a collision, the new key is placed into one of the linked lists. For applying a hash function to the sorting process, we assume that a hashing function T with the property that : z1 < z2 ⇒ T(z1) <= T(z2) When such a function is used to hash a particular key into a particular address to which previous keys have already been hashed, the new key is placed in the set of colliding records to preserve the order of the keys. Function, which follows above property, is called a nondecreasing or order-preserving, hashing function. Finally concatenate the nonempty linked lists into one. Let us consider the sample key set : 34 56 78 12 45 3 90 23 74 61 84 Now apply the above hashing function in which all keys within the ranges 1-15, 16-30, 31-45, 46-60, 60-75 and 75-90 are each hashed into a different set. As a result, we have six ordered sets as shown in table 4.1.

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

270 Data Structures

Table 4.1 Address Calculating Sorting
Set Keys in the set

1-15 → 12 3 23 16-30 34 → 45 30-45 56 46-60 61 → 74 61-75 78 → 84 → 90 75-90 These six ordered sets are merged to obtained the desired sorted list. We can use the separate chaining method of collision resolution with a separate hash table to represent the sorting process. The following table 4.2 shows the variables, which can be used for implementing address calculation sort algorithm. Table 4.2 Variables and Their Function
Variable Function

Size of the hash table Address of the first record in the sorted table HASH_TABLE(pointer) Vector of pointers representing the hash table HASH(integer) Hashing function RECORD(record) Overflow area record K(integer) Key of a record DATA(string) Other relevant informations in a record LINK(pointer) Location of the next record in the list KEY(integer) Key of the input record INFO(string) Other relevant informations of the input record RANDOM(integer) Hash address of input record NEW(pointer) Address of newly created overflow record (A) Algorithm : This algorithm sorts the records based on address calculation using a hash table with a separate overflow area. The sorted table generated is in the form of a linked list. Steps : The steps to be taken are as follows : (a) [Initialise hash table entries] Repeat for(i=1;i<=n;i++) HASH_TABLE[i] = NULL (b) [Input and insert records into the appropriate linked lists] Repeat step (c) to (d) until all records input

n(integer) HEAD(pointer)

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 271

(c) [Read and hash a record] Read(KEY,INFO) NEW ← RECORD K(NEW) ← KEY DATA(NEW) ← INFO LINK(NEW) ← NULL RANDOM ← HASH(KEY) (d) [Insert record into appropriate linked list] if (HASH_TABLE[RANODM] = NULL) (Insert record into empty linked list) LINK(NEW) ← HASH_TABLE[RANDOM] HASH_ATBLE[RANDOM] ←NEW else (Insert record in middle or at end of linked list) P ← HASH_TABLE[RANDOM] S ←LINK(P) Repeat while S ≠ NULL and K(S) < KEY P←S S ← LINK(S) LINK(P) ← NEW LINK(NEW) ←S (e) [Find first nonempty linked list] i←1 Repeat while HASH_TABLE[i] = NULL and i<n i ← i +1 HEAD ← HASH_TABLE[I] j←i+1 (f) [Concatenate the nonempty linked lists] Repeat while j ≤ n If HASH_TABLE[j] ≠ NULL then (Find tail of the linked list) P ←HASH_TABLE[i] Repeat while LINK(P) ≠ NULL P ← LINK(P) (Link tail of this linked list to the head of the next) LINK(P) ← HASH_TABLE[j] i←j j←i+1 (g) End. (B) Analysis : In the best case, the hashing function is uniformly distributed. The address calculation sort performs in a linear fashion as each key is assigned to its proper linked list and some extra work is

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

272 Data Structures

required to place the key within the linked list. In such case, the sort is O(n). In the worst case, when all keys are mapped to the same location, significant work is to be done to place a key properly within the linked list and the sort is O(n2). 4.2.7 Heap Sort : The basic approach of heap sort is to turn an unordered list into a heap, and then to keep dequeuing elements from the heap until it is empty. Because, a deletion always causes the next highest element to be moved to the root, the process of dequeuing will produce an ordered list. The space advantage of heap sort is obtained by placing each element, we delete from the heap, at the end of the unsorted section of the list (in a similar way to selection sort’s strategy of swapping values to the beginning of the list). In this way, we do not have to create another array to place the sorted elements (merge sort requires such an array). However, the first phase of a heap sort involves building the heap from an unordered list. We can take the advantage of the fact that no deletions will intervene to create a more efficient insert routine that again reorders a single array instead of copying from one array to another. 4.2.7.1 Building a Heap : We can build a heap by starting with the middle element of an unordered array and treating that element as the root of a sub-tree within the heap, we try and insert the element in its correct order in the sub-tree(moving down from the sub-tree root). Because, we are moving values up the heap as we search for the correct position for our element, we are correctly ordering other elements with respect to the element, we are adding. For this reason, we can start in the middle of an unordered list and work backwards to the root and at the end of the process, we have created a valid heap. This means, we perform n/2 insertions instead of n as we had been using our earlier insertion routine. For example, consider the unordered list : 1 2 3 4 5 6 7 8 12 34 17 33 19 22 11 10 12

34

17

33 10

19

22

11

Fig. 4.1

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 273

We start with the middle element (33) and try to insert it within its own sub-tree. It is already in a correct position (33 > 10), so we continue by moving back to 17. As 17 < 22 we move 22 up and replace it with 17 : 1 2 3 4 5 6 7 8 12 34 22 33 19 17 11 10 12 34 22

33

19

17

11

10 Fig. 4.2 Next, we move back to 34 which is > both 33 and 19, so nothing need be done and finally, we test 12 which is < 34 so we move 34 up. As 12 is also greater than 33, 33 goes up and 12 replaces it to produce the final heap : 1 2 3 4 5 6 7 8 34 33 22 12 19 17 11 10 34 33 22

12

19

17

11

10 Fig. 4.3 4.2.7.2 Sorting a Heap : The strategy is to copy 34 to the end of the list (so it replaces 10) and then try to insert 10 in the tree, starting at the root. So, after removing 34 the tree would be as follows : 33 39 22

12 34

10

17

11

Fig. 4.4

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

274 Data Structures

1

2

3

4

5

6

7

8

33 19 22 12 10 17 11 34 We would now take 33 and place it in the position currently occupied by 11, and then try inserting 11 at the root : 22

19

17

12 34

10

11

33

Fig. 4.5

1

2

3

4

5

6

7

8

22 19 17 12 10 11 33 34 Now take 22 and place it in the position currently occupied by 11, and then try inserting 11 at the root : 19

12

17

11 34

10

22

33

Fig. 4.6

1

2

3

4

5

6

7

8

19 12 17 11 10 22 33 34 Repeat the process taking 19 and place it in the position currently occupied by 10, and then try inserting 10 at the root :

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 275

17

12

10

11 34

19

22

33

Fig. 4.7

1 2 3 4 5 6 7 8 17 12 10 11 19 22 33 34 Repeat the process, take 17 and place it in the position currently occupied by 11, and then try inserting 11 at the root : 12

11

10

17 34

19

22

33

Fig. 4.8

1 2 3 4 5 6 7 8 12 11 10 17 19 22 33 34 Repeat the process, take 12 and place it in the position currently occupied by 10, and then try inserting 10 at the root : 11

10

12

17 34

19

22

33

Fig. 4.9

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

276 Data Structures

1

2

3

4

5

6

7

8

11 10 12 17 19 22 33 34 Repeat the process, take 11 and place it in the position currently occupied by 10, and then try inserting 10 at the root : 10

11

12

17 34

19

22

33

Fig. 4.10

1

2

3

4

5

6

7

8

10 11 12 17 19 22 33 34 It is clear that by repeating this strategy, we will finally arrive at a sorted list. (A) Equivalent C Function void InsertFromHeap (int pos,int array[],int n) { int k,right,left,max,temp; for(k=pos;;) { left=2*k+1; right=left+1; if(left>=n) { return; } else if(right>=n) { max=left; } else if(array[left]>array[right]) {

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 277

max=left; } else { max=right; } if(array[k]>array[max]) { return; } temp=array[k]; array[k]=array[max]; array[max]=temp; k=max; } } void HeapSort(int array[],int n) // Perform heap sort { int i,temp; for(i=n/2;i>=0; --i) // Heapify -Theta(n) { InsertFromHeap(i,array,n); } // Time Complexity: Theta(n) for(i=n-1;i>0;i--) // Time Complexity: Theta(n*lg(n)); { temp=array[0]; array[0]=array[i]; array[i]=temp; InsertFromHeap(0,array,i); } } (B) Implementation of Heap Sort Function : The following program sort_heap.c implements the heap sort function using the array of integers : /* sort_heap.c */ #include <stdio.h> #include <stdlib.h> #define N 100 void Input(int array[],int n); void InsertFromHeap(int pos,int array[],int n); void HeapSort(int array[],int n); // Perform heap sort void Print(int array[],int n);

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

278 Data Structures

void main() { int n,array[N]; printf("!!!This program sorts the array of integers using heap sort algorithm!!!\n"); printf("Please enter how many numbers are there in the array:\n"); scanf("%d",&n); Input(array,n); HeapSort(array,n); Print(array,n); } void InsertFromHeap(int pos,int array[],int n) { int k,right,left,max,temp; for(k=pos;;) { left=2*k+1; right=left+1; if(left>=n) { return; } else if(right>=n) { max=left; } else if(array[left]>array[right]) { max=left; } else { max=right; } if(array[k]>array[max]) { return; }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 279

temp=array[k]; array[k]=array[max]; array[max]=temp; k=max; } } void HeapSort(int array[],int n) { int i,temp; for(i=n/2;i>=0; --i) { InsertFromHeap(i,array,n); } for(i=n-1;i>0;i--) { temp=array[0]; array[0]=array[i]; array[i]=temp; InsertFromHeap(0,array,i); } } void Input( int array[],int n) { int i; printf("Please enter the number of the array:\n"); for (i=0;i<n;i++) scanf("%d",&array[i]); printf("Array before sorting: "); for(i=0;i<n;++i) printf("%d ",array[i]); printf("\n"); } void Print(int array[],int n) { int i; printf("Array after sorting: "); for(i=0;i<n;++i) { printf("%d ",array[i]); } printf("\n"); }

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

280 Data Structures

4.3 COMPLEXITY OF THE ALGORITHM
An algorithm is a well-defined set of steps for solving a particular problem. Our task is to develop efficient algorithms for the processing of data. The analysis of an algorithm is a major task in computer science. In order to compare algorithm, we must have some criteria to measure the efficiency of our algorithm. The time and space are the two measures for an efficient algorithm. The time is measured by counting the number of key operations. In sorting algorithms, for example, the number of comparisons. The space is measured by counting the maximum of memory needed by the algorithm. The complexity of an algorithm is the function, which gives the running time and/or storage space requirement of the algorithm in terms of the size of the input data. The storage space required by an algorithm is simply a multiple of the data size. The complexity of the sorting algorithm measures the running time as a function of the number n of items to be sorted. Normally, the complexity function measures only the number of comparisons, since the number of other operations is at most a constant factor of the number of comparisons. The following table 4.3 shows the complexity of the various sorting algorithms : Table 4.3 Complexity of Sorting Methods
Sorting Method Best Case Average Case Worst Case

Bubble Sort Selection Sort Inserted Sort Quick Sort Merge Sort Address Calculation Sort Heap Sort

O(n ) O(n2) O(n) O(n log n) O(n log n) O(n) O(n log n)

2

O(n ) O(n2) O(n2) O(n log n) O(n log n) O(n log n) O(n log n)

2

O(n2) O(n2) O(n2) O(n2) O(n log n) O(n2) O(n log n)

EXERCISE
Q.1. What is the purpose of writing the more complicated code to do binary searches, when a linear one will not only find the item if it is there, but does not even require the data to be sorted in the first place? Q.2. Rewrite the bubble sort and the merge sort to produce the list in reverse order (largest to smallest). Q.3. Implement a shell sort and a quick sort for the type cardinal (as in the text) and the type real. Which factors make the performances different for the type real? What conclusions can you draw?

Sushma Jaiswal,Lecturer S.O.S. in Computer Science,           Pt. Ravishankar Shukla University,Raipur

 

Sorting Algorithms 281

Q.4. Write a program that will read an array of strings from a disk file, sort it, and write it back. Q.5. Modify the shell sort as finally shown in the text to use a stored array for the k-sequence. To begin with, have the program ask you for the sequence from the keyboard. Test various sequences and try to find an optimum one. Once you have this, organize your work in modules as with your k-sequence safely tucked away in the implementation part. Q.6. Suppose instead of using the middle item for the pivot in a quick sort, one uses the median of the left, middle, and right items instead. Write and test this modification, determining whether or not there is a performance increase or decrease for random and already sorted arrays. Q.7. Implement a merge sort to combine the contents of two previously created files into a single file, without holding the entire sorted array in memory. Q.8. Write a recursive algorithm for merge sort and show how merge sort sorts the sequence 4,31,1,6,7,2,4,9. Q.9. Write a recursive algorithm for quick sort and show quick sort would sort the array 4,31,1,6,9,3,5,8. Q.10. Implement selection sort algorithm for linked lists. What is the time and space complexity? Q.11. Implement merge sort algorithm to merge two linked lists. Sort the concatenated list. What is its time complexity?

**

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

5
5.1 INTRODUCTION

GRAPHS

This chapter covers graphs, along with their related definitions likedefinition of graph, adjacent vertices, paths, cycles and trees etc. Various types of graphs like- directed, undirected, connected, strongly connected, weakly connected, unconnected, simple and multi graphs etc., are discussed. Graph representation includes- adjacency matrix, adjacency list and adjacency multilists. In traversal schemes, depth first search and breadth first searches are discussed. Shortest path problem with dijkstra algorithm is discussed. Minimum spanning tree with their prim’s and kruskal’s algorithm are also covered.

5.2 GRAPH
A graph G is a set of vertices(nodes) V and a set of edges(arcs) E, which connect them. Vertices on the graph are shown as points or circles and edges are drawn as arcs or line segments. We write: G = (V,E) where V is the finite and non empty set of vertices and the set of edges, E = { (vi,vj) } where vi and vj are pair of vertices in V. Therefore, V(G), read as V of G, is a set of vertices, and E(G), read as E of G, is a set of edges. A graph may be pictorially represented as shown in figure 5.1.
5

1

3

2
Fig. 5.1 A Graph

4

We have numbered the nodes as 1,2,3,4 and 5. Therefore, V(G) = (1,2,3,4,5) and E(G) = {(1,2), (1,3), (1,5), (2,3), (2,4), (3,4), (3,5) }

5.3 ADJACENT VERTICES
Two vertices are said to be adjacent if there is an edge between them, i.e, vertex v1 is said to be adjacent to a vertex v2 if there is an edge (v1, v2 ) or ( v2, v1).
(282)

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 283

The adjacent vertices of graph shown in figure 5.2 are tabulated in the table 5.1.
1 3 5 2
Fig. 5.2

4

Table 5.1 Adjacent Vertices
Vertex Adjacent Vertices

1 2 3 4 5

2,3 1,3,4 1,4,5 2,3,5 3,4

5.4 PATHS
A path P of length k, through a graph is a sequence of connected vertices, each adjacent to the next. If v0 is the initial vertex and vk is the terminal vertex, the path from v0 to vk is the sequence of vertices so that v0 is adjacent to v1, v1 is adjacent to v2 … and vk-1 is adjacent to vk. The number of edges on the path is called path length. Once again, consider the graph as shown in the figure 5.2. Some of the paths and lengths are tabulated in the table 5.2. Table 5.2
Initial Vertex Terminal Vertex Path Length

1

4

2

5

1,2,4 1,3,4 1,3,5,4 1,2,3,4 2,4,5 2,3,5 2,3,4,5 2,1,3,5

2 2 3 3 2 2 3 3

5.5 CYCLES
A cycle is a path in which first and last vertices are the same. A graph contains no cycles, if there is no path of non-zero length through the graph, P = <v0,v1,...,vk> such that v0 = vk. Let us consider the graph shown in the figure 5.2. We may notice that there is a path, which starts at vertex 1 and finishes at vertex 1, i.e., path 1,2,4,5,3,1. Such a path is called a cycle.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

284 Data Structures

5.6 VARIOUS TYPES OF GRAPHS
The graphs are classified in the following categories : (i) Directed Graph : A graph in which every edge is directed is called a directed graph or a digraph. In a directed graph, each edge is an ordered pair of vertices, i.e., a directed pair represents each edge. If E = (v,w), then v is the tail or initial vertex of the edge and w is the head or final vertex of the edge. Subsequently (v,w) and (w,v) represent two different edges. A directed graph may be pictorially represented as given in figure 5.3. An arrow indicates the direction.
5

1

3

2

4

Fig. 5.3 A Directed Graph

The set of vertices V(G) = (1,2,3,4,5} and the set of edges E(G) = {(1,2), (1,3), (1,5), (2,3), (2,4), (3,4), (5,3)}. (ii) Undirected Graph : A graph in which there is no direction between two vertices is called an undirected graph. In an undirected graph, pair of vertices representing any edge is unordered. There can be two ways of representation of edges. Thus, (v,w) and (w,v) represent the same edge. An undirected graph may be pictorially represented as shown in figure 5.4.
5

1

3

2

4

Fig. 5.4 An Undirected Graph

We have numbered the nodes as 1,2,3,4 and 5. Therefore, V(G) = (1,2,3,4,5) and E(G) = {(1,2),(1,3), (1,5), (2,3), (2,4), (3,4), (3,5) }.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 285

You may notice that the edge incident with node 1 and node 5 is written as (1,5); we could also have written (5,1) instead of (1,5). The same applies to all the other edges. Therefore, we may say that ordering of vertices is not significant here. So, we can also represent the set of edges as : E(G) ={(2,1),(3,1), (5,1), (3,2), (4,2), (4,3), (5,3) } (iii) Connected Graph : A graph is called connected, if there exists a path from any vertex to any other vertex, i.e., every pair of its vertices is connected. The figure 6.4 depicts a connected graph, as there exist a path from any vertex to any other vertex. A connected graph may consist of only one or more than one connected components. (a) Strongly Connected Graph : Two vertices are strongly connected, if they are connected in both directions to one another. A digraph is called strongly connected, if every pair of its vertices is strongly connected. Let us consider a directed graph as shown in figure 5.5. It is a strongly connected graph because every pair of vertices is strongly connected, i.e., they are connected in both directions to one another. The table 5.3, sets the paths between pair of vertices. Table 5.3
Pair of Vertices Path

1,2 1,3 1,4 1,5 2,1 2,3 2,4 2,5 3,1 3,2 3,4 3,5 4,1 4,2 4,3 4,5 5,1 5,2 5,3 5,4

1->2 1->2->4->3 1->2->4 1->5 2->4->3->1 2->4->3 2->4 2->4->3->5 3->1 3->2 3->2->4 3->5 4->3->1 4->3->2 4->3 4->3->5 5->1 5->1->2 5->1->2->4->3 5->1->2->4

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

286 Data Structures

5 3 1

4

2

Fig. 5.5 Strongly Connected Graph

(b) Weakly Connected Graph : Two vertices are weakly connected, if they are not connected in both directions to one another. A digraph is called weakly connected, if every pair of its vertices is not strongly connected. The directed graph in figure 5.6 is weakly connected. There does not exist a directed path from vertex 2 to vertex 1; also from vertex 5 to other vertices; and so on. Therefore, it is a weakly connected graph.
5

1

3

2

4

Fig. 5.6 A Weakly Directed Graph

(iv) Unconnected Graph : A graph is called an unconnected graph, if there exist at least two vertices with no path between them. Figure 5.7 is an example of unconnected graph.
1 4

2

3

5

6

Fig. 5.7 Unconnected Graph

It is an unconnected graph. We may say that these are two graphs and not one. Look at the figure in its totality and apply the definition of graph. Does it satisfy the definition of a graph? It does. Therefore, it is one graph having two unconnected components. Since, there are unconnected components, it is an unconnected graph.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 287

(v) Simple and Multi Graph : A graph is said to be simple, if only one edge is directed from any one vertex to any other vertex. Otherwise it is called multi graph. Figure 5.8 shows such graphs.
u v 4

5

6

Fig. 5.8 Simple and Multi Graph

5.7 TREES
A Tree is a special type of graph. A graph is called a tree, if it has two properties : (i) It is connected. (ii) There are no cycles in the graph. Figure 5.9 shows a graph called as tree.
1 4

7

2

3

5

6

8

9

10
Fig. 5.9 Trees

5.8 GRAPH REPRESENTATIONS
Graph is a mathematical structure and finds its application in many areas of interest in which problems need to be solved using computers. Thus, this mathematical structure must be represented as some kind of data structures. The following representations are used for representations of graph : 5.8.1 Adjacency Matrix : Suppose G=(V,E) is a graph with n vertices(nodes) and suppose the nodes of the graph have been ordered and are called v1,v2,….vn. Then the adjacency matrix A of graph G, is an nxn matrix of bits, such that : 1 Aij = 0 if there is no such edge. if there is an edge from vi to vj, i.e, vi is adjacent to vj

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

288 Data Structures

The matrix likes A, which contains entries of only 0 and 1, is called a bit matrix or a boolean matrix. The adjacency matrix A of the graph G does depend on the ordering of the nodes of G; i.e., a different ordering of the nodes may result in a different adjacency matrix. However, the resulting matrix from two different ordering can be interchanged from one to another by interchanging rows and columns. 5.8.1.1 Adjacency Matrix for Undirected Graph : The adjacency matrix A of an undirected graph G will be a symmetric matrix, i.e., Aij = Aji for every i and j. Let us take an undirected graph shown in figure 5.10. The adjacency matrix for the graph is tabulated in the table 5.4.
1 3 5 2
Fig. 5.10

4

Table 5.4 Adjacency Matrix
Vertex 1 2 1 2 3 4 5

0 1 1 0 1 1 0 1 1 0 3 1 1 0 1 1 4 0 1 1 0 0 5 1 0 1 0 0 We may observe that the adjacency matrix for an undirected graph is symmetric, as the lower and upper triangles are the same. Also, all the diagonal elements are zero. 5.8.1.2 Adjacency Matrix for Directed Graph : The adjacency matrix A of a directed graph G will be a matrix, in which Aij != Aji unless there are two edges, one in either direction, between i and j. Let us take a directed graph shown in figure 5.11. The adjacency matrix for the graph is tabulated in the table 5.5.
1 3 5 2 Fig. 5.11 4

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 289

Table 5.5 Adjacency Matrix for Directed Graph
Vertex 1 2 3 4 5 1 2 3 4 5

0 0 0 0

1 0 0 0

1 1 0 0

0 1 1 0

0 0 1 1

0 0 0 0 0 The total number of 1's account for the number of edges in the digraph. The number of 1's in each row gives the out degree of the corresponding vertex. In C language, adjacency matrix can be implemented as a 2dimensional array of type int. We may have a declaration like : #DEFINE vertex 20 typedef struct graph_tag{ int n; int adjmat[vertex][vertex]; }graph; where n is the number of nodes in the graph. adjmat[vertex][vertex] =1 if vertex are adjacent adjmat[vertex][vertex] =0 otherwise 5.8.2 Adjacency List Representation : Adjacency lists are lists of nodes that are connected to a given node. For each node, a linked list of nodes connected to it can be set up. In this representation, we store a graph as a linked structure. We store all the vertices in a list and then for each vertex, we have a linked list of its adjacent vertices. Let us consider the directed graph G given in figure 5.12.
1 4 6

2

3 5 Fig. 5.12

The adjacency list representation needs a list of all of its nodes and for each node a linked list of its adjacent nodes. Therefore, 1 2 3 4 5 6

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

290 Data Structures

1 2 3 4 5 6

→ → → → →

2 3 4 5 4

3

4

6

Fig. 5.13 Adjacency List Structure for Graph in Fig. 5.12

The adjacent vertices may appear in the adjacency list in arbitrary order. Also, an arrow from 2 to 3 in the list linked to 1, does not mean that 2 and 3 are adjacent. 5.8.3 Adjacency Multilists : In some situations, it is necessary to be able to determine the second entry for a particular edge and mark that edge as have been examined. It can be accomplished easily, if the adjacency list is actually maintained as multilist. It is a list in which nodes may be shared among several lists. There is exactly one node for each edge and this node is on the adjacency list for each of the two vertices it is incident to. Declaration for Adjacency Multilists : The following is the declaration of the adjacency multilists : #define MAX_VERTICES 20 typedef struct edge *edge_pointer; typedef struct edge { short int marked; int vertex1, vertex2; edge_pointer path1, path2; }; edge_pointer graph[MAX_VERTICES];

5.9 MINIMUM PATH PROBLEM
In many applications, we are often required to find a shortest path, i.e., a path having the minimum weight between two vertices. It turns out that it is just as easy to solve the more general problem of starting at one vertex called the source and finding the shortest path to every other vertex instead of just one destination vertex. We have seen in the graph traversals that we can travel through edges of the graph. It is very much likely in applications that these edges have some weights attached to it. This weight may reflect distance, time or some other quantity that corresponds to the cost we incur when we travel through that edge. For example, in the graph in figure 5.14, we can go from 1 to 5 through 3 at a cost of 7 or through 2 and 4 at a cost of 11.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 291

2 1 4 2 2
Figure 5.14

3 5 3 4 4 5 5

We can use the following algorithm to find the minimum path for directed graph in which every edge has a non-negative weight attached.

5.10 TRAVERSAL SCHEMES OF A GRAPH
A graph traversal means visiting all the nodes of the graph. Graph traversal may be needed in many application areas and there may be many methods for visiting the vertices of the graph. Two graph traversal methods are : 5.10.1 Depth First Traversal : In this method, we start with vertex say, v. An adjacent vertex is selected and a depth first search is initiated from it. For example, let v1, v2 .. vk are adjacent vertices to vertex v. We may select any vertex from this list. Say, we select v1. Now all the adjacent vertices to v1 are identified and all of those are visited; next v2 is selected and all its adjacent vertices visited and so on. This process continues till all the vertices are visited. It is possible that we reach a traversed vertex second time. Therefore, we have to set a flag somewhere to check, if the vertex is already visited. Let us consider a graph shown in figure 5.15.
v2 v1 v3 v4 v5 v6

Fig 5.15 Graph for DFS

The table 5.6 tabulates the adjacency matrix of graph 5.15. Table 5.6 Vertex v1 v2 v3 v4 v5 v6 v1 0 1 1 0 0 0 v2 1 0 1 1 1 0 v3 1 1 0 1 1 0 v4 0 1 1 0 1 1 v5 0 1 1 1 0 1 v6 0 0 0 1 1 0

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

292 Data Structures

The table 5.7 shows the process of visiting each vertex in the graph shown in the figure 5.15. Table 5.7
Vertices Visited Adjacency Vertices Next Non-Visited Vertex

v1 v1, v2 v1, v2 , v3 v1, v2 , v3, v4 v1, v2 , v3, v4 ,v5

v2, v3 v1, v3 , v4, v5 v1, v2 , v4, v5 v2, v3 , v5, v6 v2, v3 , v4, v6

v2 v3 v4 v5 v6

v1, v2 , v3, v4 ,v5, v6 v4, v5 NULL Let us start with v1. Its adjacent vertices are v2 and v3. Let us pick v2. Its adjacent vertices are v1, v3, v4 and v5. v1 is already visited. Let us pick v3. Its adjacent vertices are v1, v2, v4 and v5. v1 and v2 are 20 already visited. Let us visit v4. Its adjacent vertices are v2 , v3, v5 and v6. v2 and v3 are already visited. Let us traverse v5. Its adjacent vertices are v2, v3, v4 and v6. v2 , v3 and v4 are already visited. So, visit v6. We had v4 and v5 both are visited. Therefore, we back track. Now, we have visited all the vertices. Therefore, the sequence of traversal is: v1, v2, v3, v4, v5, v6.This is not a unique or the only sequence possible for using this traversal method. Declaration : The following is the structure declaration for depth first search algorithm : #define v 10 typedef int adj_matrix[v][v]; typedef struct t_graph{ int nodes[v]; int n_nodes; int *visited; adj_matrix am; }graph; Where nodes represent the traversal order of the vertices of the graph, n_nodes represent the total nodes in the graph, visited is the flag, which is used to indicate whether the vertex of the graph is visited or not and am is used to represent the adjacent matrix of the graph. The following is the algorithm which implements the depth first search process of traversing a node within the graph(G). (A) Algorithm : Following are the steps for depth first search : (a) [Initialise the counter with zero for storing the arrival vertices of the graph]

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 293

Set index = 0 (b) [Enter the vertices in the graph] Read(n_nodes) (c) [Initialise all vertices in the array with FALSE to indicate the absence of visits to the vertices] Repeat step (d) for(i=1;i<n_nodes;i++) (d) Set visited[i] = FALSE (e) [Read adjacent matrix of the graph, enter 1 in the array for all adjacent vertices j of vertex i and 0 for not] Repeat step (f) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (f) Read am[i][j] (g) [Check each vertex of the graph whether it is visited or not] Repeat step from (h) for(i=1;i<n_nodes;i++) (h) If(!visited(i)) then Call function visit(g,i) (i) [Print the adjacent matrix of the graph] Repeat step (m) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (j) Write a[i][j] (k) [Print the sequence of traversal of a given graph] Repeat step (o) for(i=1;i<n_nodes;v++) (l) Write nodes[i] (m) [Definition of the function DFS] void visit(g, i) (n) Set visited[i] = TRUE Set nodes[++index] = i (o) [Check all the vertices adjacent to the vertex i] Repeat step (p) for(j=1;j<n_nodes;j++) (p) If(am[i][j] == 1) then If(!visited(j)) then Call visit(g, j) recursively (q) End. (B) Equivalent Function in C void DFS( graph *g ) { int i,j,k; /*Initialise all the vertices of the graph with FALSE to indicate the absence of visits to the vertices*/ for(k=1;k<=g->n_nodes;k++) g->visited[k] = FALSE;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

294 Data Structures

/* Read the adjacent matrix of the graph*/ for(i=1;i<=g->n_nodes;i++) { for(j=1;j<=g->n_nodes;j++) { scanf("%d",&g->am[i][j]); } } /*check the vertex of the graph is visited or not */ for(k=1;k<=g->n_nodes;k++) { if ( !g->visited[k] ) /* Call function visit */ visit(g, k); } /* Print the adjacency matrix of the graph !!*/ for(i=1;i<=g->n_nodes;i++) { for(k=1;k<=g->n_nodes;k++) { printf("%d\t",g->am[i][k]); } printf("\n"); } /*The sequence of traversal of a given graph in DFS */ i=0; while(i<g->n_nodes) { printf("%d\t",g->nodes[++i]); } } void visit( graph *g, int k ) { int j; /*assign the vertex of the graph is visited */ g->visited[k] = TRUE; g->nodes[++search_index] = k; /* Search for visited vertex */ for(j=1;j<=g->n_nodes;j++) { /* Check adjacent vertex of the vertex */

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 295

if(g->am[k][j] == 1) { /*check the vertex of the graph is visited or not */ if (!g->visited[j]) /* Call recursively function vists */ visit( g, j ); } } } (C) Implementation of the Depth First Search Method : The following program graph_dfs.c performs the traversal operation of the graph using depth first search method. A depth first traverse of a graph uses an additional array to flag nodes that it has visited already : /*graph_dfs.c*/ #include<stdio.h> #define v 10 #define FALSE 0 #define TRUE 1 typedef int adj_matrix[v][v]; typedef struct t_graph { int nodes[v]; int n_nodes; int *visited; adj_matrix am; }graph; void DFS(graph *); void visit(graph *,int); static int search_index=0; void main() { graph g; printf("This program performs the traversal of graph using depth first search method!!\n"); printf("Please enter the nodes in the graph\n"); scanf("%d",&g.n_nodes); DFS(&g); } void DFS( graph *g ) { int i,j,k; for(k=1;k<=g->n_nodes;k++)

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

296 Data Structures

g->visited[k] = FALSE; for(i=1;i<=g->n_nodes;i++) { for(j=1;j<=g->n_nodes;j++) { printf("Please enter data of vertex %d for(%d,%d):\n",i,i,j); printf("Please enter 1 for adjacent vertex and 0 for not\n"); scanf("%d",&g->am[i][j]); } } for(k=1;k<=g->n_nodes;k++) { if ( !g->visited[k] ) visit(g, k); } printf("!!ADJACENCY MATRIX!!\n"); for(i=1;i<=g->n_nodes;i++) { for(k=1;k<=g->n_nodes;k++) { printf("%d\t",g->am[i][k]); } printf("\n"); } i=0; printf("!!The sequence of traversal of a given graph in DFS is!!\n"); while(i<g->n_nodes) { printf("%d\t",g->nodes[++i]); } } void visit( graph *g, int k ) { int j; g->visited[k] = TRUE; g->nodes[++search_index] = k; for(j=1;j<=g->n_nodes;j++) { if(g->am[k][j] == 1)

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 297

{ if (!g->visited[j]) visit( g, j ); } } } (D) Output of the Program This program performs the traversal of graph using depth first search method!! Please enter the nodes in the graph 6 Please enter data of vertex 1 for(1,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 1 for(1,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 1 for(1,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 1 for(1,4): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 1 for(1,5): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 1 for(1,6): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 2 for(2,1): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,2): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 2 for(2,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,4): Please enter 1 for adjacent vertex and 0 for not 1

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

298 Data Structures

Please enter data of vertex 2 for(2,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,6): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 3 for(3,1): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,3): 0 Please enter data of vertex 3 for(3,4): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,6): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 4 for(4,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 4 for(4,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,4): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 4 for(4,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,6): Please enter 1 for adjacent vertex and 0 for not 1

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 299

Please enter data of vertex 5 for(5,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 5 for(5,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 5 for(5,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 5 for(5,4): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 5 for(5,5): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 5 for(5,6): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 6 for(6,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 6 for(6,2): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 6 for(6,3): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 6 for(6,4): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 6 for(6,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 6 for(6,6): Please enter 1 for adjacent vertex and 0 for not 0 !!ADJACENCY MATRIX!! 0 1 1 0 0 0 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 0 0 0 1 1 0

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

300 Data Structures

!!The sequence of traversal of a given graph in DFS is!! 1 2 3 4 5 6 5.10.2 Breadth First Traversal : In this method, we start with vertex say, v. Visit v and then visit all the adjacent vertices of the vertex v and then visit all the unvisited vertices adjacent to these and so on. This process continues till all the vertices are visited. It is possible that we reach a traversed vertex second time. Therefore, we have to set a flag somewhere to check, if the vertex is already visited. Let us consider a graph shown in figure 5.16.
v1 v5 v3 v4 v2

Fig 5.16 Graph for BFS

The table 5.8 tabulates the adjacency matrix of graph shown in figure 5.16. Table 5.8 Vertex v1 v2 v3 v4 v1 0 1 1 0 v2 1 0 1 1 v3 1 1 0 1 v4 0 1 1 0 v5 1 0 1 0

v5 1 0 1 0 0 We start with vertex say, v1. Its adjacent vertices are v2, v3 and v5. We visit all one by one. The list of visited vertices is v1, v3, v4 and v5. Now, we pick one of these, say v2. Its adjacent vertices are v1, v3 and v4. The unvisited adjacent vertex to v2 is v4. We visit v4. We go back to the remaining visited vertices of v1. There are no more unvisited adjacent vertices of v3, v4 and v5. Therefore, the sequence of traversal is: v1, v2, v3, v5, v4. Declaration : The following is the structure declaration for breath first search algorithm ; #define v 10 typedef int adj_matrix[v][v]; typedef struct t_graph{ int n_nodes;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 301

int *visited; adj_matrix am; }graph; Where n_nodes represent the total nodes in the graph, visited is the flag, which is used to indicate whether the vertex of the graph is visited or not and am is used to represent the adjacent matrix of the graph. The following is the algorithm, which implements the breath first search process of traversing a node within the graph(G). (A) Algorithm: Following are the steps for breadth first search algorithm : (a) [Initialise the counter with zero for storing the arrival vertices of the graph] Set index = 0 (b) [Enter the vertices in the graph] Read(n_nodes) (c) [Initialise all vertices in the array with FALSE to indicate the absence of visits to the vertices] Repeat step (d) for(i=1;i<n_nodes;i++) (d) Set visited[i] = FALSE (e) [Read adjacent matrix of the graph, enter 1 in the array for all adjacent vertices j of vertex i and 0 for not] Repeat step (f) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (f) Read am[i][j] (g) [Check each vertex of the graph whether it is visited or not] Repeat step from (h) to (n) for(i=1;i<n_nodes;i++) (h) If(!visited(i)) then Call insert_queue(q, i) (i) [Check all the vertices adjacent to the vertex i] Repeat step from (j) to (n) while(front!=rear) (j) Set k = delete_queue(q) (k) Set visited[i] = TRUE (l) [Check adjacent vertex of the graph whether it is visited or not] Repeat step from (m) to (n) for(j=1;j<n_nodes;j++) (m) If(am[i][j] == 0) then continue (n) [Check all the vertices adjacent to the vertex i] If(!visited(j)) then Set visited[j] = TRUE, Call insert_queue(q, j) (o) [Print the adjacent matrix of the graph]

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

302 Data Structures

Repeat step (m) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (p) Write a[i][j] (q) [Print the sequence of traversal of a given graph] Repeat step (o) for(i=1;i<n_nodes;v++) (r) Write q[i] (s) End. (B) Equivalent function in C void BFS( graph *g ) { int k,i,j; /*Initialise all the vertices of the graph with FALSE to indicate the absence of visits to the vertices*/ for(k=1;k<=g->n_nodes;k++) g->visited[k] = FALSE; /* Read the adjacent matrix of the graph*/ for(i=1;i<=g->n_nodes;i++) { for(j=1;j<=g->n_nodes;j++) { scanf("%d",&g->am[i][j]); } } /*check the vertex of the graph is visited or not */ for(k=1;k<=g->n_nodes;k++) { if ( !g->visited[k] ) { /* Insert visited vertex in the queue */ insert_queue(q,k); do { /* Delete vertex from the queue */ k = delete_queue(q); /*assign the vertex of the graph is visited*/ g->visited[k] = TRUE; for(j=1;j<=g->n_nodes;j++) { /* Check adjacent vertex of the vertex */ if(g->am[k][j] == 0) continue;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 303

/*check the vertex of the graph is visited or not */ if (!g->visited[j]) { /*assign the vertex of the graph is visited */ g->visited[j] = TRUE; /* Insert visited vertex in the queue */ insert_queue(q, j); } } }while(front!=rear); } } /* Print the adjacency matrix of the graph !!*/ for(i=1;i<=g->n_nodes;i++) { for(k=1;k<=g->n_nodes;k++) { printf("%d\t",g->am[i][k]); } printf("\n"); } /*The sequence of traversal of a given graph in BFS is*/ i=0; while(i<g->n_nodes) { printf("%d\t",q[++i]); } } (C) Implementation of the Breath First Search Method : The following program graph_bfs.c performs the traversal operation of the graph using breath first search method. A breath first traverse of a graph uses an additional array to flag nodes that it has visited already : /*graph_bfs.c*/ #include<stdio.h> #define v 10 #define FALSE 0 #define TRUE 1 typedef int adj_matrix[v][v]; typedef struct t_graph{ int n_nodes; int *visited;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

304 Data Structures

adj_matrix am; }graph; void BFS(graph *); void insert_queue(int[],int); int delete_queue(int[]); int front=1,rear=1; int q[v]; void main() { graph g; printf("This program performs the traversal of graph using breath first search method!!\n"); printf("Please enter the nodes in the graph\n"); scanf("%d",&g.n_nodes); BFS(&g); } void BFS( graph *g ) { int k,i,j; for(k=1;k<=g->n_nodes;k++) g->visited[k] = FALSE; for(i=1;i<=g->n_nodes;i++) { for(j=1;j<=g->n_nodes;j++) { printf("Please enter data of vertex %d for(%d,%d):\n",i,i,j); printf("Please enter 1 for adjacent vertex and 0 for not\n"); scanf("%d",&g->am[i][j]); } } for(k=1;k<=g->n_nodes;k++) { if ( !g->visited[k] ) { insert_queue(q,k); do { k = delete_queue(q); g->visited[k] = TRUE;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 305

for(j=1;j<=g->n_nodes;j++) { if(g->am[k][j] == 0) continue; if (!g->visited[j]) { g->visited[j] = TRUE; insert_queue(q, j); } } }while(front!=rear); } } printf("!!ADJACENCY MATRIX!!\n"); for(i=1;i<=g->n_nodes;i++) { for(k=1;k<=g->n_nodes;k++) { printf("%d\t",g->am[i][k]); } printf("\n"); } i=0; printf("!!The sequence of traversal of a given graph in BFS is!!\n"); while(i<g->n_nodes) { printf("%d\t",q[++i]); } } void insert_queue(int q[], int k) { q[rear] = k; rear++; } int delete_queue(int q[]) { int item; item = q[front]; front++; if(front==v) { front=1; rear=1;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

306 Data Structures

} return(item); } (D) Output of the Program This program performs the traversal of graph using breath first search method!! Please enter the nodes in the graph 5 Please enter data of vertex 1 for(1,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 1 for(1,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 1 for(1,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 1 for(1,4): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 1 for(1,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,1): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,2): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 2 for(2,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,4): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 2 for(2,5): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 3 for(3,1): Please enter 1 for adjacent vertex and 0 for not 1

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 307

Please enter data of vertex 3 for(3,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,3): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 3 for(3,4): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 3 for(3,5): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,1): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 4 for(4,2): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 4 for(4,4): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 4 for(4,5): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 5 for(5,1): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 5 for(5,2): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 5 for(5,3): Please enter 1 for adjacent vertex and 0 for not 1 Please enter data of vertex 5 for(5,4): Please enter 1 for adjacent vertex and 0 for not 0 Please enter data of vertex 5 for(5,5): Please enter 1 for adjacent vertex and 0 for not 0

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

308 Data Structures

!!ADJACENCY MATRIX!! 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 0 1 0 1 0 0 !!The sequence of traversal of a given graph in BFS is!! 1 2 3 5 4

5.11 SPANNING TREES
A spanning tree of a connected graph G is a connected sub-graph of G having no cycles. Every connected graph has a spanning tree. Let us formally define a spanning tree. A tree T is a spanning tree of a connected graph G(V,E) such that : (i) every vertex of G belongs to an edge in T, (ii) the edges in T form a tree. Let us see how we construct a spanning tree for a given graph. Take any vertex v as an initial partial tree and add edges one by one so that each edge joins a new vertex to the partial tree. In general, if there are n vertices in the graph we shall construct a spanning tree in (n- 1) steps i.e., (n- 1) edges are needed to be added. For example, the following graph has four distinct spanning trees :
v1 v2

v3
Fig. 5.17

v4

Spanning Trees:
v1 v2 v1 v2

v3 v1

v4 v2

v3 v1

v4 v2

v3

v4
Fig. 5.18

v3

v4

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 309

5.12 APPLICATIONS OF GRAPH
Graph is an important data structure whose extensive applications are known in almost all application areas. Nowadays, many applications related with computation can be managed efficiently with graph structures. In this section we have discussed two of them. 5.12.1 Minimum Spanning Tree Problem : Suppose the edges of the graph have weights or lengths. The weight of a tree is just the sum of weights of its edges. Obviously, different trees have different lengths. The cost of the spanning tree is the sum of the cost of all edges in the tree. We usually want to find a spanning tree of minimum cost. Among all the spanning trees of a weighted and connected graph, the one (possibly more) with the least total weight is called a minimum spanning tree (MST). (i) Computer Networks : Vertices in the graph might represent computer installations, edges represent connections between computers. We want to allow messages from any computer to get to any other, possibly with routing through an intermediate computer, with minimum cost in connections. (ii) Airline Routes : Vertices in the graph are cities, and edges are routes between cities. We want to service a connected set of cities, with minimum cost. The minimum spanning tree problem is the simplest, and one of the most central models in the field of combinatorial problem. It has inspired the development of many other problem domains in discrete optimisation. In many systems, such as highways, computer networks, telephone lines, television cables, etc., we face such a problem: we need to design a simplest network(spanning tree) that will connect geographically dispersed system components so that they can communicate with each other and the total construction cost is minimised. This is only a situation where the minimum spanning tree problem can be applied directly. Actually, there are lots of indirect applications of the minimum spanning tree problem, such as, optimal message passing, all-pairs mini-max path, reducing data storage, cluster analysis, etc. Suppose we have a group of islands that we wish to link with bridges so that it is possible to travel from one island to any other in the group. Further suppose that (as usual) our government wishes to spend the absolute minimum amount on this project (because other factors like the cost of using, maintaining, etc., these bridges will probably be the responsibility of some future government). The engineers are able to produce a cost for a bridge linking each possible pair of islands. The set

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

310 Data Structures

of bridges, which will enable one to travel from any island to any other at minimum capital cost to the government, is the minimum spanning tree and for finding the minimum spanning tree is the minimum spanning tree problem. The following are the algorithms, which can be used for finding the minimum spanning tree : 5.12.1.1 Prims Algorithm : This algorithm for finding a minimal cost spanning tree in a connected graph is very easy to follow. It begins by adding the lowest cost edge and its two end points to the solution set. It then loops adding the lowest cost edge that connects a vertex in the solution set to one outside it. It also adds the end point of this edge that is not already in the solution set. The algorithm terminates when all vertices are in the solution set. The edges and vertices in the solution set at this point constitute a minimal cost spanning tree of the input graph. This method does not require listing of all nodes in increasing order of weights and does not require to check at each step whether a newly selected node forms a circuit or not. The prim’s algorithm can be easily implemented using the adjacency matrix representation of a graph. Declaration : The following is the structure declaration for prim’s algorithm : #define v 10 typedef struct t_tree { int n_nodes; int path[v]; int tree[v][v]; int selected[v]; int adj_matrix[v][v]; }tree; Where n_nodes represent the total nodes in the tree, selected is the flag, which is used to indicate whether the vertex of the graph is visited or not, adj_matrix is used to represent the cost from one vertex to another, tree is an array, which stores the output of the minimum spanning tree in an adjacency matrix and path represent the path of the minimum spanning tree. The following is the algorithm, which implements the prim’s algorithm of tree (T) : (A) Algorithm : Following are the steps for prim’s algorithm. (a) [Read the vertices in the graph] Read(n_nodes) (b) [Read adjacent matrix of the graph. The weight will be taken infinity, if there is no direct path between one vertex to another vertex, we have used 1500 for infinity, enter cost 0 for vertex to itself]

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 311

Repeat step (c) for(i=0;i<n_nodes;v++), for(j=0;j<n_nodes;j++) (c) Read adj_matrix[i][j] (d) [Write the adjacent matrix of the graph] Repeat for(i=0;i<n_nodes;i++) Repeat for(j=0;j<n_nodes;j++) Print(adj_matrix[i][j]) (e) [Initially none of the vertices are selected] for(i=0;i<n_nodes;i++) Set selected[i] = FALSE (f) [Initially enters 0 in the minimum spanning tree matrix] for(i=0;i<n_nodes;i++) for(j=0;j<n_nodes;j++) Set tree[i][j]=0 (g) [Select the vertex 0 as the starting vertex] Set selected[0]=TRUE, path[0]=0, length = 1 (h) [Find the nearest neighbour vertex of one of selected vertices] Repeat step (i) to (n) while(length<=n_nodes) (i) Set min = INFINITY (j) Repeat step(k) to (m)for(i=0;i<n_nodes;i++) (k) If(selected[i]==TRUE) then (l) Repeat step(m) for(j=0;j<n_nodes;j++) (m) If(selected[j]==FALSE) then If(adj_matrix[i][j] <min) then Set min = adj_matrix[i][j], u = i, w = j, (n) [Include the nearest neighbour into the tree] Set tree[u][w] = 1, selected[w] = TRUE, path[++k] = w, length = length + 1 (o) [ Write the minimum spanning tree adjacency matrix] Repeat for(i=0;i<n_nodes;i++) Repeat for(j=0;j<n_nodes;j++) Print(tree[i][j]) (p) [Write the shortest path from the source to all vertices] Repeat for(i=0;i<k;i++) Print(path[i]) (q) End.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

312 Data Structures

(B) Equivalent Function in C void prim(tree *t) { int i,j,k=0,w,u,p,min; /* Read the cost matrix */ for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { scanf("%d",&t->adj_matrix[i][j]); } } /*THE ADJACENT MATRIX OF THE GRAPH IS: */ for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { printf("%5d\t",t->adj_matrix[i][j]); } printf("\n"); } /* Initially none of the vertices are selected */ for(i=0;i<t->n_nodes;i++) { t->selected[i] = FALSE; } /* Initially enters 0 in the minimum spanning tree matrix */ for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { t->tree[i][j]=0; } } /* Select the vertex 0 as the starting vertex */ t->selected[0]=TRUE; t->path[0]=0; length = 1; /*Find the nearest neighbour vertex of one of the selected vertices*/ while(length<=t->n_nodes) {

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 313

min = INFINITY; for(i=0;i<t->n_nodes;i++) { if(t->selected[i]==TRUE) { for(j=0;j<t->n_nodes;j++) { if(t->selected[j]==FALSE) { if(t->adj_matrix[i][j] <min) { min = t->adj_matrix[i][j]; u = i; w = j; } } } } } /* Include the nearest neighbour into the tree */ t->tree[u][w] = 1; t->selected[w] = TRUE; t->path[++k] = w; length++; } /* End of While loop */ /* the minimum spanning tree adjacency matrix is*/ for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { printf("%5d\t",t->tree[i][j]); } } /* print the shortest path from the source to all vertices */ for(i=0;i<k;i++) printf("%d\t",t->path[i]); } 5.12.1.2 Operation of Prim’s Algorithm : Let us take an undirected weighted graph and its weighted adjacency matrix as shown in figure 5.19. The following sequence of diagrams depicts the operation of prim’s algorithm :

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

314 Data Structures

Source 2 4 4 3 6 10 0

Graph 5 3 6 1 2 1

Adjacency Matrix 0 0 1 2 3 4 5 3 2 1 5 1 6 6 2 3 1 2 10 3 6 2 4 4 2 6 10 4 -

2 0

Initial Tree 4

1 We start with source node 0.

3 2 4 0

2 Choose the closest node to 0. We locate the vertex closest to it, i.e., we find a vertex from the adjacent vertices of 0 for which the length of the edge is minimum. 4, 2 and 1 are the adjacent vertices of 0. Vertex 4 has the minimum length(04)=2. Therefore, we choose 4.

1

3 0

2 Now we look for all the adjacent vertices excluding the just earlier vertex of newly added vertex and the remaining adjacent vertices of earlier vertices, i.e., we have 1, 2 and 3 (as adjacent vertices of 4) and 1, 2 (as remaining adjacent vertex of 0). Now we again compare the length of the paths from source vertex to these unattached vertices. We find the length(02)=3 is the minimum. Therefore, we choose vertex 2.

2

3 4 1

3

2

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 315

2 4

0 3

1 1

3 Final stage 2 4 0 3

2

Now we have 1 and 3 (as adjacent vertices of 2) 3 and 1 (as remaining adjacent vertex of 4) and 1 (as remaining adjacent vertex of 0). Now we again compare the length of the paths from source vertex to these unattached vertices. We find the length(21)=1 is the minimum. Therefore, we choose vertex 1. Now we have 3 (as adjacent vertices of 1) 3 (as remaining adjacent vertex of 2) and 3 (as remaining adjacent vertex of 4). Now we again compare the length of the paths from source vertex to these unattached vertices, We find the length(23)=2 is the minimum. Therefore, we choose vertex 3. The total length of the tree can be calculated as 8.
Fig. 5.19

1 1

3

2

2

(A) Implementation of the Prim’s Algorithm : The program tree_prim.c finds the minimum spanning tree of the given undirected graph using prim’s algorithm. The distances will be taken infinity if there is no direct path from one vertex to another vertex. We have used 1500 for infinity, we can use constant INT_MAX defined in <limits.h>. If there is no arrowhead from a vertex to itself the distance is taken as 0. /*tree_prim.c*/ #include<stdio.h> #include<limits.h> #define INFINITY INT_MAX #define v 10 #define FALSE 0 #define TRUE 1 typedef struct t_tree { int n_nodes; int path[v]; int tree[v][v]; int selected[v]; int adj_matrix[v][v]; }tree;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

316 Data Structures

void prim(tree *); void main() { tree t; printf(“This program finds the minimum spanning tree of a undirected graph using prim’s algorithm!!\n”); printf(“Please enter how many edges in the graph:\n”); scanf(“%d”,&t.n_nodes); prim(&t); } void prim(tree *t) { int i,j,k=0,w,u,min,length; for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { printf(“Please enter weight for visiting edge %d to edge %d:”,i,j); scanf(“%d”,&t->adj_matrix[i][j]); } } printf(“THE ADJACENT MATRIX OF THE GRAPH IS\n”); for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { printf(“%5d\t”,t->adj_matrix[i][j]); } printf(“\n”); } for(i=0;i<t->n_nodes;i++) { t->selected[i] = FALSE; } for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { t->tree[i][j]=0; } } t->selected[0]=TRUE;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 317

t->path[0]=0; length = 1; while(length<=t->n_nodes) { min = INFINITY; for(i=0;i<t->n_nodes;i++) { if(t->selected[i]==TRUE) { for(j=0;j<t->n_nodes;j++) { if(t->selected[j]==FALSE) { if(t->adj_matrix[i][j] <min) { min = t->adj_matrix[i][j]; u = i; w = j; } } } } } t->tree[u][w] = 1; t->selected[w] = TRUE; t->path[++k] = w; length++; } printf(“THE MINIMUM SPANNING TREE ADJANCENCY MATRIX IS\n”); for(i=0;i<t->n_nodes;i++) { for(j=0;j<t->n_nodes;j++) { printf(“%5d\t”,t->tree[i][j]); } printf(“\n”); } /* print the shortest path from the source to all vertices */ printf(“The minimum spanning tree path using prim’s algorithm is\n”); for(i=0;i<k;i++) printf(“%d\t”,t->path[i]);

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

318 Data Structures

printf(“\n"); } (B) Output of the Program This program finds the minimum spanning tree of a undirected graph using prim's algorithm!! Please enter how many edges in the graph: 5 Please enter weight for visiting edge 0 to edge 0: 0 Please enter weight for visiting edge 0 to edge 1: 5 Please enter weight for visiting edge 0 to edge 2: 3 Please enter weight for visiting edge 0 to edge 3: 1500 Please enter weight for visiting edge 0 to edge 4: 2 Please enter weight for visiting edge 1 to edge 0: 5 Please enter weight for visiting edge 1 to edge 1: 0 Please enter weight for visiting edge 1 to edge 2: 1 Please enter weight for visiting edge 1 to edge 3: 6 Please enter weight for visiting edge 1 to edge 4: 6 Please enter weight for visiting edge 2 to edge 0: 3 Please enter weight for visiting edge 2 to edge 1: 1 Please enter weight for visiting edge 2 to edge 2: 0 Please enter weight for visiting edge 2 to edge 3: 2 Please enter weight for visiting edge 2 to edge 4: 10 Please enter weight for visiting edge 3 to edge 0: 1500 Please enter weight for visiting edge 3 to edge 1: 6 Please enter weight for visiting edge 3 to edge 2: 2 Please enter weight for visiting edge 3 to edge 3: 0 Please enter weight for visiting edge 3 to edge 4: 4 Please enter weight for visiting edge 4 to edge 0: 2 Please enter weight for visiting edge 4 to edge 1: 6 Please enter weight for visiting edge 4 to edge 2: 10 Please enter weight for visiting edge 4 to edge 3: 4 Please enter weight for visiting edge 4 to edge 4: 0 THE ADJACENT MATRIX OF THE GRAPH IS 0 5 3 1500 2 5 0 1 6 6 3 1 0 2 10 1500 6 2 0 4 2 6 10 4 0 THE MINIMUM SPANNING TREE ADJANCENCY MATRIX IS 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 319

The minimum spanning tree path using prim's algorithm is 0 4 2 1 3 5.12.1.3 Kruskal's Algorithm : The kruskal algorithm starts with a forest, which consists of n single node trees(no edges). In every step of the algorithm, two different trees of this forest are connected to a bigger tree. Therefore, we keep having less and bigger tree in our forest until we end up in a tree which is the minimum spanning tree. In every step, we choose the side with the least cost, if the chosen side connects nodes, which belong to the same tree. The side is rejected and not examined again because it could produce a circle, which will destroy our tree. Either this side or the next one in order of least cost will connect nodes of different trees and this way we connecting two small trees into a bigger one. (A) Algorithm : Let us take an undirected weighted graph G with n vertices. Let the spanning tree T is initially empty. E is the array that contains the edges of the graph G in the increasing order of weights. Steps : The following are the steps for kruskal algorithm : (a) The forest is constructed with each node in a separate tree. (b) Initialise spanning tree T is empty i.e., T= 0. (c) List all the edges of the graph G in the increasing order of weights in the array E. (d) Repeat step (e) to (h) until the tree T contains n-1 edges or E is not empty. (e) Extract the cheapest edge eij from E. (f) Delete this edge eij from E E = E – {eij} (g) If eij does not create a cycle add eij to T. (h) Otherwise reject eij. (i) If T contains less than n-1 edges and the list E is empty than no spanning tree is possible for the graph G, otherwise return the minimum spanning tree T. 5.12.1.4 Operation of Kruskal Algorithm : The following sequence of diagrams illustrates Kruskal's algorithm in operation. Let us consider the undirected graph G shown in figure 5.20. 5 v2 v5 4 3 3 v1 v6 1 2 4 2 1
v3

6
Fig. 5.20

v4

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

320 Data Structures

Construct forest with each node in a separate tree :
v2 v1 v3
Fig. 5.21

v5 v6 v4

List all the edges of the graph G in the increasing order of weights in the array E. E=1122334456 Extract the cheapest edge from E i.e., v2-v3 and v4-v6. Delete these edges from E and add it into spanning tree because, it will not create cycle. Now, the remaining edges are E = 2 2 3 3 4 4 5 6
v2 v1 v5 v6

1 1
v3
Fig. 5.22

v4

Extract the next cheapest edge from E i.e., v1-v3 or v2-v4. Delete these edges from E and add it into spanning tree because, it will not create cycle. Now, E = 3 3 4 4 5 6
v2 v1 v5

1 2
v3

2 1
v4
Fig. 5.23

v6

Now extract the next cheapest edge from E i.e. v5-v6 or v3-v5. Delete these from E and add it v5-v6 into spanning tree because, it will not create cycle discard v3-v5 because, it will create cycle. Now, E=4 4 5 6
v2 v1 v5

3 1 2
v3
Fig. 5.24

2 1
v4

v6

Now spanning tree contains n-1 edges and the remaining edges create cycle so discard these edges and stop the process. The resulting spanning tree is the minimum spanning tree with total weight 9 shown in fig 5.24.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 321

5.12.2 Shortest Path Problem : The problem of a graph for finding a path between two vertices V1 and V2 in such a way that this path will satisfy some criteria of optimisation is called shortest path problem. This is solved using a technique called Dijkstra’s algorithm. 5.12.2.1 Dijkstra's Algorithm : E.W. Dijkstra’s discovered Dijkstra's algorithm, to solve the problem of finding the shortest path from a point on a graph (the source) to a destination. It turns out that one can find the shortest paths from a given source to all points on a graph in the same time, hence this problem is sometimes called the single-source shortest path problem. Declaration : The following is the structure declaration for dijkstra’s algorithm : #define v 10 typedef struct t_graph { int n_nodes; int D[v]; int visited[v]; int path[v]; int adj_matrix[v][v]; }graph; Where n_nodes represent the total nodes in the graph, visited is the flag, which is used to indicate whether the vertex of the graph is visited or not, cost is used to represent the cost from one vertex to another, path represent the shortest path from source to other vertices and D is the array of best estimates of shortest path to each vertex of the graph. The following is the algorithm, which implements the Dijkstra’s algorithm within the graph(G) : (A) Algorithm : The following steps are taken for Dijkstra’s algorithm : (a) [Read the of vertices in the graph] Read(n_nodes) (b) [Read adjacent cost matrix of the graph.The cost will be taken infinity, if there is no direct path between one vertex to another vertices, we have used 1500 for infinity, enter cost 0 for vertex to itself] Repeat step (c) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (c) Read cost[i][j] (d) [Assign source vertex is visited and enters this vertex in the array of best estimate D and shortest path array path] Set visited[0]=TRUE, D[0]=0,

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

322 Data Structures

path[0] = 0 (e) [Set remaining vertices are unvisited and assigns the cost of remaining vertices from source vertex, into the array of best estimate D] for(u=1;u<n_nodes;u++) Set visited[u] = FALSE, D[u] = cost[0][u] (f) Repeat step (g) to (j) for(i=1;i<n_nodes;i++) Set min = INFINITY (g) [Find the closest vertex u to vertex 0] for(w=1;w<n_nodes;w++) if(!visited[w]) if(D[w] <min) Set u = w, min = D[w] (h) [Add vertex u to the set of visited vertices] Set visited[u] = TRUE; (i) [Update the remaining costs in D] for(w=1;w<n_nodes;w++) if(!visited[w]) if((min + cost[u][w])< D[w]) D[w] = min + cost[u][w] path[k] = u (j) [Write the shortest path from the source to all other vertices] for(p=0;p<=k;++p) write path[p] k++ (k) End. (B) Equivalent Function in C void dijkstra(graph *g) { int i,j,k=0,w,u,p,min; /* Read the cost matrix */ for(i=0;i<g->n_nodes;i++) { for(j=0;j<g->n_nodes;j++) { scanf("%d",&g->cost[i][j]); } } /*THE ADJACENT COST MATRIX IS: */ for(i=0;i<g->n_nodes;i++) {

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 323

for(j=0;j<g->n_nodes;j++) { printf("%5d\t",g->cost[i][j]); } printf("\n"); } /* Assign the source vertex 0 in the set of visited vertices */ g->visited[0]=TRUE; g->D[0]=0; g->path[0] = 0; printf("%d\n",g->path[0]); k++; for(u=1;u<g->n_nodes;u++) { g->visited[u] = FALSE; g->D[u] = g->cost[0][u]; } /* Start the main loop, add one vertex u to S on each pass */ for(i=1;i<g->n_nodes;i++) { min = INFINITY; /* Find the closest vertices u to vertex 0 */ for(w=1;w<g->n_nodes;w++) { if(!g->visited[w]) if(g->D[w] <min) { u = w; min = g->D[w]; } } /* Add u to the set S */ g->visited[u] = TRUE; /* Update the remaining distances in D */ for(w=1;w<g->n_nodes;w++) if(!g->visited[w]) if(min + g->cost[u][w]<g->D[w]) g->D[w] = min + g->cost[u][w]; g->path[k] = u; /* print the shortest path from the source to other vertices */ for(p=0;p<=k;++p) printf("%d\t",g->path[p]); k++;

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

324 Data Structures

printf("\n"); } } 5.12.2.2 Operation of Dijkstra's Algorithm : The following sequence of diagrams illustrates the operation of Dijkstra's algorithm : Source 0 2 4 4 3 6 10 3 6 1 2 5 1 2 In initial graph we start with source vertex 0.

2 0

2 4 D=2 3

5 1 D=5

Choose the closest node to 0. We locate the vertex closest to it, i.e., we find a vertex from the adjacent vertices of 0 for which the length of the edge is minimum. 4, 2 and 1 are the adjacent vertices of 0. Vertex 4 has the minimum length(04)=2. Therefore, we choose 4.

3

2 D=3

2 6 4 4 3

0 3

5 1

10 2

Now we have 1, 2 and 3 (as adjacent vertices of 4) and 1, 2 (as remaining adjacent vertex of 0). Now we again compare the length of the paths from source vertex to these unattached vertices, i.e., compare length(01)=5,length(02)=3,length(041)=8,l ength(042)=12 and length(043)=6. We find the length(02)=2 is the minimum. Therefore, we choose vertex 2.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 325

0 2 4 4 3 6 3 5 1 1 2

2

Now we have 1 and 3 (as adjacent vertices of 2) 3 and 1 (as remaining adjacent vertex of 4) and 1 (as remaining adjacent vertex of 0). Now we again compare the length of the paths from source vertex to these unattached vertices, i.e., compare length(021)=4,length(023)=5,length(04 1)=8, length(043)=6 and length(01)=5. We find the length(021)=4 is the minimum. Therefore, we choose vertex 1. Now we have 3 (as adjacent vertices of 1) 3 (as remaining adjacent vertex of 2) and 3 (as remaining adjacent vertex of 4). Now we again compare the length of the paths from source vertex to these unattached vertices, i.e., compare length(0213)=10, length(023)=5, length(043)=6. We find the length(023) is the minimum. Therefore, we choose vertex 3. shortest paths from to all the other vertices

2 4 4 3

0 3 6 1 2

1

2

2 4 D =2

0 3

1 3 D=5 2 D=3

Therefore, the source vertex 0 are : 0 1 0 4 D=4 0 4 2 0 4 2 0 4 2

1 1

3

2

Fig. 5.25

(A) Implementation of the Dijkstra’s Algorithm : The program tree_dijkstra.c finds the shortest path of the given directed graph using Dijkstra’s algorithm. The distances will be taken infinity if there is no direct path from one vertex to another vertex. We have used 1500 for infinity, we can use constant INT_MAX defined in <limits.h>. If there is no arrowhead from a vertex to itself the distance is taken as 0.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

326 Data Structures

/*tree_dijkstra.c*/ #include<stdio.h> #include<limits.h> #define INFINITY INT_MAX #define v 10 #define FALSE 0 #define TRUE 1 typedef struct t_graph { int n_nodes; int path[v]; int D[v]; int visited[v]; int adj_matrix[v][v]; }graph; void dijkstra(graph *); void main() { graph g; printf("This program finds the shortest path of a directed graph using Dijkstra's algorithm!!\n"); printf("Please enter how many vertices in the graph:\n"); scanf("%d",&g.n_nodes); dijkstra(&g); } void dijkstra(graph *g) { int i,j,k=0,w,u,p,min; for(i=0;i<g->n_nodes;i++) { for(j=0;j<g->n_nodes;j++) { printf("Please enter cost for visiting vertex %d to vertex %d:",i,j); scanf("%d",&g->cost[i][j]); } } printf("THE ADJACENT COST MATRIX IS: \n"); for(i=0;i<g->n_nodes;i++) { for(j=0;j<g->n_nodes;j++) { printf("%5d\t",g->cost[i][j]); }

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 327

printf("\n"); } printf("The shortest path of the graph is :\n"); g->visited[0]=TRUE; g->D[0]=0; g->path[0] = 0; printf("%d\n",g->path[0]); k++; for(u=1;u<g->n_nodes;u++) { g->visited[u] = FALSE; g->D[u] = g->cost[0][u]; } for(i=1;i<g->n_nodes;i++) { min = INFINITY; for(w=1;w<g->n_nodes;w++) { if(!g->visited[w]) if(g->D[w] <min) { u = w; min = g->D[w]; } } g->visited[u] = TRUE; for(w=1;w<g->n_nodes;w++) if(!g->visited[w]) if(min + g->cost[u][w]<g->D[w]) g->D[w] = min + g->cost[u][w]; g->path[k] = u; for(p=0;p<=k;++p) printf("%d\t",g->path[p]); k++; printf("\n"); } } (B) Output of the Program This program finds the shortest path of a directed graph using Dijkstra's algorithm!! Please enter how many vertices in the graph: 5 Please enter cost for visiting vertex 0 to vertex 0: 0

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

328 Data Structures

Please enter cost for visiting vertex 0 to vertex 1: 5 Please enter cost for visiting vertex 0 to vertex 2: 3 Please enter cost for visiting vertex 0 to vertex 3: 1500 Please enter cost for visiting vertex 0 to vertex 4: 2 Please enter cost for visiting vertex 1 to vertex 0: 1500 Please enter cost for visiting vertex 1 to vertex 1: 0 Please enter cost for visiting vertex 1 to vertex 2: 2 Please enter cost for visiting vertex 1 to vertex 3: 6 Please enter cost for visiting vertex 1 to vertex 4: 1500 Please enter cost for visiting vertex 2 to vertex 0: 1500 Please enter cost for visiting vertex 2 to vertex 1: 1 Please enter cost for visiting vertex 2 to vertex 2: 0 Please enter cost for visiting vertex 2 to vertex 3: 2 Please enter cost for visiting vertex 2 to vertex 4: 1500 Please enter cost for visiting vertex 3 to vertex 0: 1500 Please enter cost for visiting vertex 3 to vertex 1: 1500 Please enter cost for visiting vertex 3 to vertex 2: 1500 Please enter cost for visiting vertex 3 to vertex 3: 0 Please enter cost for visiting vertex 3 to vertex 4: 1500 Please enter cost for visiting vertex 4 to vertex 0: 1500 Please enter cost for visiting vertex 4 to vertex 1: 6 Please enter cost for visiting vertex 4 to vertex 2: 10 Please enter cost for visiting vertex 4 to vertex 3: 4 Please enter cost for visiting vertex 4 to vertex 4: 0 THE ADJACENT COST MATRIX IS: 0 5 3 1500 2 1500 0 2 6 1500 1500 1 0 2 1500 1500 1500 1500 0 1500 1500 6 10 4 0 THE SHORTEST PATH OF THE GRAPH IS : 0 0 4 0 4 2 0 4 2 1 0 4 2 1 3

EXERCISE
Q.1. Write a C program for kruskal’s minimum spanning tree algorithm. Q.2. Give an example of a connected graph such that removal of any edge results in a graph that is not connected.

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

Graphs 329

Q.3. Consider the graph given in the figure below :
v2 v5 v4 v1 v3 v6 v7 v8

(a) Is there a path from A to Z that passes through each vertex exactly once? (b) What is the maximum number of vertices one can visit once in going from A to Z? Q.4. Find the degree of each vertex of the graph given below :
v2 v6

v1

v3

v7

v9

v4

v5

v8

Is it possible to trace the above graph, beginning and ending at the same point, without lifting your pencil from the paper and without retracing lines? Justify your answer. Q.5. In the given graph : 2 3
B C D

1

5 3

7

6

7

2

A

E

G

J

L

4

7
F

4
I

3

4
K

5

2

6

Sushma Jaiswal,Lecturer S.O.S. in Computer  Science, Pt. Ravishankar Shukla University,Raipur

[2010] 

330 Data Structures

Find the length of the shortest path and the shortest path between : (i) A and F (ii) A and Z (iii) D and H. Q.6. Write a program that accepts adjacency matrix as an input and outputs a list of edges given as pairs of positive integers. Q.7. Draw minimum cost spanning tree for the graph given below and also find its cost. 2
B C

2

2

4

3

1

A

D

4 3

F

H

1

3
E

7
G

5

Q.8. Find the shortest paths from source vertex to all the vertices for the graph given in the above figure using dijkstra’s algorithm. Q.9. Show the visiting of all the nodes of the given graph using DFS and BFS traversal schemes.
v2 v1 v3 v4 v5 v6

**

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

1.Algorithm Of Traversing 1-Dimensional Array. This algorithm traverses a linear array LA with lower bound LB and upper bound UB. Step 1: Step 2: Step 3: Step 4: Step 5: [Initialze counter] Set K = LB. Repeat Set 3 and 4 While K <= UB. [Visit element] Apply PROCESS To LA[K]. [Increase counter] Set K = K+1. [End Of Step 2 Loop] Exit.

1

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

2 ALGO TO DELETE ELEMENT FROM 1-D ARRAY Step1: Set Item=LA[k] Step2: Repeat for j=k to n-1 [ move j+1 element upward] set LA[j] = LA[j+1]. [End Of Loop] Step3: [Rset the number N of element in LA] Set N =N -1. Step4: Exit.

2

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

3.ALGORITHM:-(Inserting into a linear array) INSERT (LA,N,K,ITEM) Here LA is a linear array with an element and K is a positive integer such that K <= N This algorithm insert an element item into the Kth position in LA. Step 1: Step 2: Step 3: Step 4: [Initialize counter] Set J = N. Repeat Step 3 And 4 While J >= K. [Move Jth element downward]. Set LA [J+1] = LA[J]. [Decrease Counter] Set J = J-1. [End Of Step 2 Loop]. [Insert element] Set LA[K] = ITEM. [Reset N] Set N = N+1. Exit.

Step 5: Step 6: Step 7:

3

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

4. ALGORITHM TO TRAVERS IN 2-DIMENSION ARRAY. [This algorithm traverses a two dimensional array TD with lower bound LB and upper bound UB.] Step1> Step2> Repeat For A=LB To UB. Repeat For B=LB To UB. Apply Process to TD[A][B]. [End Of Loop.] Exit.

Step3>

4

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

5.ALGORITHEM TO DELETE ELEMENT 2-D ARRAY STEP1: STEP2: set Item=LA[a][b] Repeat for i=a to n-1 [move i+1 element upward] set LA[j]=LA[i+1] [End of loop] Step3: Repeat for j=b to n-1 [Move j+1 element upward] Set LA[j]=LA[j+1] [End of loop] Step4: [Reset the number n of element in LA] Set n=n-1. Step5: Exit.

5

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

7. ALOGORITHM FOR STACK OPERATION. (iv) Push Operation : The push operation pushes an element on the top of the stack.
(A) Algorithm : Following are the steps for push operation of a stack : (a) [Check overflow condition]

If (TOP>=STACKSIZE) then print the stack is full and exit (b) [Insert element in new top position] S[TOP] = item (c) [Increment the pointer value TOP by one] TOP = TOP + 1 (d) End. (v) Pop Operation : The pop operation deletes or removes the topmost item from the stack.
(A) Algorithm : Following are the steps for pop operation of a stack : (a) [Check whether the stack is empty]

If (TOP<=0) then print the stack is empty and return (b) [Decrement TOP by one] TOP = TOP – 1 (c) [Assign TOP element to item] item = S[TOP] (d) [Return top most item from stack] return(item) (e) End.

6

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

10.ALGORITHM FOR INFIX EXPRESSION TO POSTFIX EXPRESSION. POLISH (Q,P) Suppose Q Is An Arithmetic Expression Written In Infix Notation. This Algorithm Finds The Equivalent Postfix Expression P. Step1: Step2: Step3: Step4: Push “(” onto STACK, And Add “)” To The End Of Q. Scan Q From Left To Right And Repeat Step3 To 6 For Each Element Of Q Until The Stack Is Empty. If An Operand Is Encounter, Put It On Stack. If An Operator Is Encounter , Then: (a) Remove The Two Top Elements Of Stack, Where A Is The Top Element And B Is The Next To Top Element. (b) Evaluate B A. (c) Place The Result Of (b) Back On Stack. [End Of If Structure.] [End Of Step 2 Loop.] Set VALUE Equal To The Top Element On Stack. Exit.

Step5: Step6:

7

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

14. ALGORITHM TO CALCULATE FACTORIAL OF A GIVEN NUMBER. Step1> Step2> Step3> Step4> Step5> Step6> Set Fact = 1 Read N. Repeat Step 3 To Step 4 For I = 1 To N. Fact = Fact *I [End Of Step 3 Loop.] Write Fact Exit.

8

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

15. Algorithm For Sum Of The Fibonacci Series : Step1> Step2> Step3> Step4> Step5> Step6> Set A = 0 , B = 1 ,C = 1 And SUM = 0. Read N. Repeat Step 4 To 6 For I = 1 To N. Write C. SUM = SUM + C. Set C = A + B. Set A = B. Set B = C. [End Of Step 3 Loop.] Write SUM. Exit.

Step7> Step8>

9

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

16. ALGORITHEM: FOR FIND GREATEST COMMON DEVISOR Step1: Definition of int GCD(in tint) function ] Set p=n%c Step2: Repeat while p!=0 Set n=c .c=p,p=n%c Return(c). Step3: [Inside main( ) function] Initialise a,b. Step4: if(a<b) then Print (GCD of “a” and “b” is GCD(a,b) ) [calling GCD( ) function ] else Print(GCD of “b” and “a” is gcd(b,a) [calling GCD( )] [End of if structure] Step5 : Exit.

10

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

17. ALGORITHM FOR TOWER OF HANOI. TOWER (N, BEG, AUX, END) Remarks-: Algorithm for Tower of Hanoi. This procedure gives a recursive solution to the Tower of Hanoi problem for N disks. Step(1)-: IF N < = 0, then : Step(1a)-: Write: Illegal Disk. Step(1b)-: Return [ End of If Structure ] Step(2)-: IF N = 1, then : Step(2a)-: Write : Transfer disks from BEG to END Step(2b)-: Return Step(3)-: ELSE Step(4)-: Call TOWER( N-1, BEG, END, AUX ) [ Move N-1 Disk peg BEG to peg AUX ]

Step(5)-: Call TOWER( 1, BEG, AUX, END ) Step(6)-: Call TOWER( N-1, AUX, BEG, END ) [ Move N-1 Disk peg AUX to Peg END ]

11

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
[ End of If Structure ] Step(7)-: Exit

18.

ALGORITHM FOR OPERATION ON QUEUE USING LINK LIST. QINSERT(QUEUE,N,FRONT,REAR,ITEM) This Procedure Insert An Element Item Into Queue. Step1: [Queue Already Filled?] If front = 1 And Rear = N Or If front = Rear +1 Then write Overflow And Return. [find New Value Of Rear.] If Front = Null Then [Queue Initially Empty] Set Front = 1 and Rear = 1. Else If Rear = N Then Set Rear = 1. Else Set Rear = Rear +1. [End Of If Structure.] Set Queue[Rear ]= ITEM. [This Insert The New Element.] Return.

Step2:

Step3: Step4:

QINSERT(QUEUE,N,FRONT,REAR,ITEM) This Procedure delet An Element Item Into Queue. Step1: [Queue Already empty?] If front = Null then write Underflow And Return. 12

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step2: If Front = Null Then [Queue Initially Empty] Set Front = 1 and Rear = 1. Else If Rear = N Then Set Rear = 1. Else Set Rear = Rear +1. [End Of If Structure.] Set Queue[Rear ]= ITEM. [This Insert The New Element.] Return.

Step3: Step4:

20.ALGORITHM FOR CIRCULAR QUEUE Insertion: 1. If Front or Rear+1=Front and Rear =Maxsize then Print “Overflow Error” Return; [End of If structure] 2. If(Rear=0) Set Rear=1 Set Front=1 Else If(Rear=Maxsize) Set Rear=Rear+1; Set CQ[Rear] = Item; Return; Deletion: 1.If (Front=NULL) Print “Underflow Error” Return; [End of If] 2.Item=CQ[Front] 3.If {Front = Rear) Set Front = NULL Set Rear = NULL Else If(Front = Maxsize) Set Front =1; 13

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Else Set Front=Front+1; Return;

21.ALGORITHM FOR OPERATION IN DOUBLE ENDED QUEUE. Add at REAR Operation:- This operation add an element at the rear of the deque. Step1> [Check Overflow condition.] If REAR >= DQSIZE, Then: Write “OVERFLOW” And Return. [Check DEQUE is Empty Or Not] If REAR = 0 And FRONT, Then: DQ[REAR]=ITEM REAR=REAR+1. [Otherwise Isert An Element Into The REAR of The Deque.] Else DQ[REAR]=ITEM. [End Of The If Structure.] [Increment The REAR Pointer By One .] REAR=REAR+1. Exit.

Step2>

Step3> Step4>

Delete From FRONT Operation:- This Operation Deletes Or Remove The Item From the Front Of The Deque. Step1> [Check UNDERFLOW Condition] If REAR=0 And FRONT=0, Then: Write “UNDERFLOW” And Return.

14

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
[Otherwise assign element from the FRONT of the Deque to ITEM and increment FRONT by 1] Else Set ITEM=DQ[ITEM]. FRONT=FRONT+1. [End Of If Structure.] [Check for Empty Deque.] If FRONT=REAR. Then: Set FRONT=0 And REAR=0. [End Of If Structure.] [Return ITEM from the FRONT of the Deque.] Return ITEM. Exit.

Step2>

Step3> Step4>

Add at FRONT Operation :-This operation adds an element at the FRONT of the Deque.] Step1> [Check OVERFLOW Condition.] If FRONT <=0, Then: Write “OVERFLOW” And Return. [End Of If Structure.] Step2> If FRONT>0, Then: [Decrement the FRONT PTR by 1.] FRONT=FRONT+1. [End Of If Structure.] Step3> [Insert an element in FRONT of the Deque.] DQ[FRONT]=ITEM. Step4> Exit. Delete from REAR Operation:- This operation deletes or remove the ITEM from the REAR of the Deque. Step1> [Check UNDERFLOW condition.] If REAR=NULL, Then: Write “UNDERFLOW” And Return. [Otherwise Decrement REAR by one and assign element frome the REAR of the Deque to ITEM.] Else REAR=REAR-1. ITEM=DQ[REAR]. [End Of If Structure] [Check Deque for Single Element.] If FRONT= REAR, Then: Set FRONT=0 And REAR=0. [End Of If Structure.] [Return ITEM from the REAR of the Deque.] Return ITEM. 15

Step2>

Step3>

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step4> Exit.

22.ALGORITHM FOR TRAVERSING IN A SINGLE LINKED LIST 1. Set PTR=START.[initializes pointer PTR.] 2. Repeat Steps 3 and 4 while PTR! =NULL. 3. Apply PROCESS to INFO [PTR]. 4. Set PTR =LINK [PTR]. [End of Step 2 loop.] 5. Exit. ALGORITHM FOR INSERTION IN LINKED LIST. INSERTION(INFO,LINK,START,AVAIL,ITEM) 1. [OVERFLOW] if AVAIL=NULL, then: Write: OVERFLOW, and Exit. 2. [Remove first node from AVAIL list.] Set NEW = AVAIL and AVAIL = LINK[AVAIL]. 3. Set INFO [NEW] = ITEM. [Copies new data into new node.] 4. Set LINK [NEW] = START. [New node now points to original first node.] 5. Set START = NEW. [Change START so it points to the new node.] 6. Exit. ALGORITHM FOR DELETE AN ITEM FROM LINKED LIST. DEL(INFO, LINK, START, AVAIL, LOC LOCP) 1.If LOCP = NULL , then: Set START = LINK[START].[Delete first node.] Else: Set LINK[LOCP] = LINK[LOC].[Delete node N.] [End of If structure.] 2.[Return deleted node to the AVAIL list.] Set LINK [LOC] =AVAIL and AVAIL = LOC; 16

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
3.Exit.

17

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
23.ALGORITHM FOR DOUBLE LINKED LIST. 1.CREATION 1. [Initialization] (a). Start.Next = NULL. (b).Previous.Next = NULL. 2. [Assign address of Start variable to Node] Node = Address of Start 3. [Make left and right links of a Node] (a).Next[Node] = Node [Make link to Node] (b).Previous [Node] = Node [Make link to Node] (c).Node = Next [Node][Move pointer to Next Node] (d).Info [Node] = value [Information value of a Node] (e).Next[node] = NULL [Assign NULL to the address field] 2.TRAVERSING 1. [Initialization] Node = Start.Next 2. [Traverse the list in forward direction] Repeat while Next [Node] != NULL. Process Info [Node] 3. [Traverse the list in backward direction] Repeat while Previous [Node] != NULL. Process Info [Node] 4. Exit. 3.INSERTION 1. [Initialization for new node] NODE = NEW[PTR]. 2. [Assign the value for new node] NEW [PTR] = Item. 3. [Assign LEFT and RIGHT links to NULL]. PTR -> Pre = Ptr -> Next = NULL 4. [Make the RIGHT link of the new node to point to head of the list , and make the Left link of the head to point to the new node.] PTR -> prev =Null; PTR -> Next =Start; Start -> Prev = PTR; 5. [Reset the header pointer ] Start = PTR. 6. Exit.

18

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

4.DELETION A NODE FROM FROM THE BEGNING 1. [Chacking of the list is empty ] if(Start = = NULL) print:”Empty list-No deletion”. 2. [Make the head pointer to point to the second node and if the second is not null then make its LEFT link to point to NULL] if(Start ->next = = NULL) set : PTR = Start. set : Start = End = NULL, else set : PTR = Start set : Start = Start->Next set : Start -> prev = NULL 3. [Free the first node] free(PTR) 5. Exit. 5.DELETION A NODE FROM THE END 1. [Chacking of the list is empty ] if(End = = NULL) print:”Empty list-No deletion”. 2. [Transverse the list till the last but one node and make the RIGHT link of the last but one node to point to NULL] if(Start ->next = = NULL) set : PTR = End. set : Start = End = NULL, else set : PTR = End set : End = End->Prev set : End-> Next = NULL 3. [Free the last node] free(PTR) 6. Exit.

19

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

24. ALGORITHM FOR CIRCULAR LINK LIST:ALGO(DATA,*NEXT,NODE,C,CHOICE) Step1> Set CHOICE =Y. Step2> Repeat Step 0 To Step 0 While (CHOICE!=N) Step3> [Create Circular List] [Function Called] CREATECIRCULARLIST(NODE) Step4> [Display List] [Function Called] DISPLAY(NODE) Step5> [Insert at Insert at Begin Of List.] [Function Called.] INSERTBEGIN(NODE) Step6> [Insert at Insert at Last of List] [Function Called] INSERTLAST(NODE) Step7> [Insert at Insert at Location Of List] [Function Called] INSERTATLOCATION(NODE) Step8> [Delete Item From list] [Function Called] DELETE(NODE) Step9> Exit. ALGO CREATECIRCULARLIST(* NODE) Step1> Set Choice=Y And Set C=0 Step2> Set START.NEXT=NULL Step3> Set NODE=&START Step4> [Allocate memory for NODE using CLIST as Structure] NODE->NEXT=(CLIST*)MALLOC(SIZE(CLIST)) Step5> Set NODE =NODE->NEXT. Step6> Repeat Step 7 To Step 12 While CHOICE !=N Step7> [Allocate Memory For NODE using CLIST as Structure] NODE->NEXT=(CLIST *)MALLOC(SIZE(CLIST)) Step8> Set NODE=NODE->NEXT Step9> Set NODE->=START.NEXT Step10> [Input The ITEM And CHOICE] INPUT NODE->DATA And INPUT CHOICE. Step11> Set C=C+1 Step12> Set START.NEXT->DATA =C. 20

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step13> [End Of While Loop] Exit.

ALGO DISPLAY(*NODE) Step1> Set 1=0 And Set NODE=START.NEXT And NODE=NODE->NEXT Step2> Repeat Step 0 To Step 0 For I=1 To C Step3> Set NODE=NODE->NEXT [End Of For Loop] Step4> Exit.

ALGO INSERTATBEGIN(*NODE) Step1> Step2> Step3> Step4> Step5> Step6> Step7> Step8> Set NODE=START.NEXT [Allocate Memory for new1 using CLIST Structure] Set NEW1=(CLIST*)MALLOC(SIZE(CLIST)) [INPUT DATA] INPUT NEW1->DATA Set NEW1->NEXT=NODE->NEXT Set NODE->NEXT=NEW1 Set START.NEXT->DATA=START.NEXT->DATA+1. Set C=C+1. Exit.

ALGO INSERTATLAST(*NODE) Step1> Set COUNT=0 And Set NODE=START.NEXT Step2> [Allocate Memory for new1 using CLIST Structure] Set NEW1=(CLIST*)MALLOC(SIZE(CLIST)) Step3> [INPUT DATA] INPUT NEW1->DATA Step4> Repeat Step 0 To Step 0 While COUNT <C Step5> Set NODE=NODE->NEXT Step6> Set COUNT=COUNT+1 Step7> Set NODE->NEXT=NEW1 Step8> Set NEW1->NEXT=START.NEXT Step9> Set START.NEXT->DATA=START.NEXT->DATA+1. [End Of While Loop] Step10> Set C=C+1. Step11> Exit. ALGO INSERTATLOC(*NODE) Step1> Set COUNT=0 And Set LOC=0 And FLAG=0 Step2> Set PREV=START.NEXT Set NODE=PREV->NEXT 21

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step3> Step4> Step5> Step6> Step7> Step8> Step9> Step10> Step11> Step12> Step13> Step14> [Allocate Memory for NEW1 using CLIST Structure] Set NEW1=(CLIST *)MALLOC(SIZE(CLIST)) [Input Data And Loc] INPUT NEW->DATA And INPUT LOC Repeat Step0 To Step0 While(NODE) If LOC=COUNT+1, Then: Set NEW1->NEXT=PREV->NEXT Set PERV->NEXT=NEW1 And Set FLAG=1 And Break. [End Of If Structure.] Set NODE=NODE->NEXT. Set PREV=PREV->NEXT Set COUNT=COUNT+1. If FLAG=0, Then: Set START.NEXT->DATA=START.NEXT->DATA+1 Set C=C+1 [End Of If Structure] [End Of While Loop.] Exit.

Step15>

ALGO DELETE(*NODE) Step1> Set COUNT=0 And Set FLAG =0 And Set LOC=0 Step2> If START.NEXT->NEXT=START.NEXT, Then: Step3> PRINT “UNDERFLOW ERROR” And Return. [End Of If Structure] Step4> [Input Location Of Data To Removed] INPUT LOC Step5> Set PRV=START.NEXT And NODE=PREV->Next Step6> Repeat Step 7 To Step 12 While NODE Step7> If LOC=COUNT+1,Then: Step8> Set PREV->NEXT=NODE->NEXT Step9> [Removal Of Memory] FREE(NODE) Step10> Set FLAG=1 And Break. [End Of If Structure] Step11> Set NODE=NODE->NEXT And PREV=PREV->NEXT Step12> Set COUNT=COUNT+1 Step13> If FLAG=0,Then Step14> Print”DATA NOT FOUNDED” [End Of If Structure] Step15> START.NEXT->DAT=START.NEXT->DATA-1 Step16> Set C=C-1 Step17> Exit.

22

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

26. ALGORITHM FOR LINKED LIST SORT. SORT( INFO, LINK, START, NODE, PTR, TEMP )

Remarks-: Algorithm for sorting the Link List. NODE and PTR are pointer variables. TEMP is the temporary variable used for swapping the numbers.

Step(1)-: Set NODE = START and PTR = LINK[ START ] [ Initializes Pointer. ] Step(2)-: Repeat Step(3) and Step(4) While NODE ≠ NULL Step(3)-: Repeat Step(4) While PTR ≠ NULL Step(4)-: IF INFO[ NODE ] > INFO[ PTR ], then : Step(4a)-: Set TEMP = INFO[ NODE ] Step(4b)-: Set INFO[ NODE ] = INFO[ PTR ] Step(4a)-: Set INFO[ PTR ] = TEMP [ End of If Structure ] [ End of Step(3) Loop ] [ End of Step(2) Loop ]

23

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

29. ALGORITHM FOR BINARY SEARCH METHOD. (Binary Search) BINARY(DATA, LB,UB,ITEM,LOC) Here Data Is A Sorted Array With Lower Bound LB And UppeBoundUB,And ITEM Is A Given Item Of Information.The Variable BEG, END And MID Denote, Respectively, The Beginning, End And Middle Locations Of A Segment Of Elements Of Data .This Algorithm Finds The Location LOC Of ITEM In Data Or Sets LOC = NULL. Step1: Step2: Step3: [Initialize Segment Variable.] Set BEG = LB,END = UB And MID = Int((BEG +End)/2). Repeat Step3 And 4 While BEG <= END And Data[MID] !=ITEM.. If ITEM < Data[MID],Then: Set BEG = MID-1. Else: Set BEG = MID+1. [End Of If Structure.] Set MID = INT((BEG + END)/2). [End Of Step 2 Loop.] If Data[MID]=ITEM,Then: Set LOC = MID. Else Set LOC = NULL. [End Of If Structure.] Exit.

Step4: Step5:

Step6:

24

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

31. INSERTION SORT
(A) Algorithm : The steps to be taken are as follows :

(a) Initialise k = 1 (b) Repeat steps (c) to (g) while(k<n) (c) Set element = array[k] (d) Initialise pos = k-1 (e) Repeat steps (f) while(array[pos]>element && pos>=0) (f) Set array[pos+1] = array[pos] (g) Set array[pos+1] = element (h) End.

25

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

32.ALGORITHM FOR SELECTION SORT. SELECTION(A, N, LOC, MIN) Remark-: Algorithm for sorting numbers through Selection Sort. A is an array with N elements. This algorithm sorts numbers in array A. Step(1) -: Repeat Step(2) and Step(3) For I = 1 to N-1 Step(2)-: Call LEAST(A, MIN, LOC, I) Step(3)-: A[LOC] : = A[ I ] and A[ I ] [ Interchange A[ I ] and A[ LOC ] ] [End of loop] Step(4)-: Exit

26

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

33. ALGORITHM FOR BUBBLE SORT.
(A) Algorithm : The steps to be taken are as follows :

(a) Initialise k = n-1 (b) Repeat steps (c) to (f) while(k>0) (c) Initialise i = 0 (d) Repeat steps (e) to (f) while(i<k) (e) [Compare the i’th element to the i+1’th element] If(array[i] > array[i+1]) then (f) Set temp = array[i] array[i] = array[i+1] array[i+1] = temp (g) End.

27

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

34.ALGORITHM TO SORT LIST OF ELEMENTS USING SHELL SORT. SHLSORT([20],FLAG ,I,J,G,N,T) Step 1: [ENTER HOW MANY ELEMENT TO BE INSERT IN AN ARRAY] INPUT N Step 2: Repeat Step(3) for(I=0;I<N;I++) Step 3: INPUT A[I} Step 4:Set FLAG = 0 Step 5:Set G =(N/2) Step 6:Repeat Step(6) to Step while(G>=1 && FLAG = =0) Step 7: Repeat Step (7) to Step (11) For (I=0;I<N-G;I++) Step 8: If(A[I] >A[I+G] Then Step 9:Set T=A[I] Step10:Set A[I] = A[I+G] Step11.Set A[I+G] =T [END OF IF STRUCTIRE] [END OF FOR LOOP] Step12: Repeat Step ( ) To Step ( ) For (J =0;j<N-1;J++) Step 13:If(A[J>A[J+1] Then Set FLAG =0 AND BREAK ELSE Set FLAG =1 28

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
[END OF IF STRUCTURE] [END OF FOR LOOP] Step 14:If(G!=1) Then Step 15:Set G = (G/2) [END OF WHILE LOOP] Step 16:Repeat Step (17) For(I=0;I<N;I++) Step 17: PRINT A[I] Step18 Exit

35. ALGORITHM FOR SORT LIST OF ELEMENTS USING QUICK SORT. (A) Algorithm : The array[] is an array with n elements. The method of sorting by partitioning a list into two sub-lists around some pivotpos, (where the items in the left sub-list are all less than the pivotpos, and those in the right sub-list are all greater than the pivotpos), and then recursively sorting the left and right sub-lists.
Steps : The steps to be taken are as follows : (a) If n<=1 then return (b) [Otherwise call function partition] pivotpos = Partition(array,n) (c) [Recursively call the function quick sort for both partitions] QuickSort(array,pivotpos) QuickSort(array+pivotpos+1,n-pivotpos-1) (d) End.

29

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

36. ALGORITHM FOR HEAPSORT. HEAPSORT(A,N) An array A with N elements is given this algorithm Sorts the elements of A. Step1> [Build a Heap H,using INSHEAP() Procedure] Repeat For J=1 To N-1. Call INSHEAP(A,J,A[J+1]]. [End Of Loop] Step2> [Sort A By repeatedly deleting the root of H,using DELHEAP() Procedure] (a) Call DELHEAP(A,N,ITEM). (b) Set A[N+1]=ITEM. [End Of Loop] Step3> Exit. Procedure:- INSHEAP(TREE,N,ITEM) Step1> Step2> Step3> Step4> [Add new node.to H and Initialize PTR.] Set N=N+1 And PTR=N. [Find location to insert ITEM] Repeat Steps 3 To 6 While PTR<1. Set PAR=[PTR/2].[Location Of Parent Node.] If ITEM<=TREE[PAR],Then: Set TREE[PTR]=ITEM And Return. [End Of If Structure.] 30

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step5> Step6> Step7> Step8> Set TREE[PTR]=TREE[PAR.] [Moves Node Down.] Set PTR=PAR[Updates PTR]. [End Of Step2 Loop.] [Assign ITEM as the root of H.] Set TREE[1]=ITEM. Return.

Procedure:-DELHEAP(TREE,N,ITEM) Step1> Step2> Step3> Step4> Step5> Set ITEM=TREE[1] [Removes root of H] Set LAST=TREE[N] And N=N-1. Set PTR=1, LEFT=2 And RIGHT=3. Repeat Steps 5 To 7 While RIGHT<=N If LAST>=TREE[LEFT] And LAST >= TREE[RIGHT], Then: Set TREE[PTR]=LAST And Return. [End Of If Structure.] If TREE[RIGHT]<=TREE[LEFT],Then: Set TREE[PTR]=TREE[LEFT] And PTR=LEFT. Else Set TREE[PTR]=TREE[RIGHT] And PTR=RIGHT. [End Of If Structure.] Set LEFT=2*PTR And RIGHT=LEFT+1 [End Of Step 4 Loop.] If LEFT =N And If LAST<TREE[LEFT], Then: Set PTR=LEFT Set TREE[PTR]=LAST Return.

Step6>

Step7> Step8> Step9> Step>

31

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

37.ALGORITHM FOR TREE OPERATION Algo( Data, Item ,Node, *Left ,*Right ,T ,Choice) Step1: Step 2: Set Item = 0 [Binary Tree ] [Function Call] BINARY TREE(NODE,ITEM) Step 3: [CreateTree ] [Function Call] CREATE TREE( T ) Step 4: [InOrderTraversing] [Function Call] INORDER ( T ) Step 5:[PreOrder Traversing] [FunctionCall] PREORDER ( T ) Step 6: [PostOrder Traversing ] [Function Call POSTORDER( T ) Step 7:Exit

ALGO BINARY TREE(*NODE ,ITEM) 32

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step 1: Step 2: If(Node = = NULL) [Allocate Memory For Node Where “Tree is structure of user Defined Datatype] Set Node = ( Tree *) Malloc (sizeof(Tree)) Set Node ->Left =Null Set Node->Right = Null Set Node->Data=Item [End of If Structure] Else If (Item<Node ->Data)Then (a)Set Node -> Left = Binary Tree(Node -> Data, Item) [Function Called By Recursion] (b)Print Node -> Left . [End Of If Structure] Node -> Right = Binary Tree(Node -> Rigth, Item). Print Node -> Right. [end Of Else If Structure] Return(Node) Return. ALGO CREATETREE (TREE*T) Step 1: Set Item = 0 and Set Choice = Y. Step 2: [Allocate Memory For Node Where “ Tree” Is Structure Of User Defined data type.] Set Node = (Tree *) Malloc(Size of (Tree)) Step 3: Set T = Null. Step 4: Repeat Step 5 To Step 6 While (Choice = Y). Step 5: [Input The Element.] Step 6: Set T = Bineary Tree (T,Tree) [Function Called By Recursion.] Step 7: Step 8: Return(T). Return.

Step 3: Step 4: Step 5: Step 6:

Step7: Step8: Step9: Step10:

ALGO DISPLAY(TREE *M,HEIGHT) Step 1: If (M) Then Step 2: Display (M -> Rigth, Height +1). Step 3: Repeat Step 4 For (I = 1 ; I <= Hieght ; I ++). Step 4: Print Space “ “. [End Of For Loop.] Step 5: Print M -> Data. Step 6: Display (M -> Left, Height + 1). [Function Called By Recursion.] Step 7: Return.

33

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
ALGO INORDER (TREE *NODE) Step1: If (Node != Null). Step 2: Inorder (Node –> Left). [Function Called By Recursion.] Step 3: Print Node -> Data. Step 4: Inorder (Node -> Right). Step 5: Return. ALGO PREORDER (TREE * NODE) Step 1: Step 2: Step 3: Step 4: Step 5: If (Node != Null). Print Node -> Data. Preorder (Node -> Left). [Function Called By Recursion.] Preorder (Node -> Right). [Function Called By Recursion.] Return.

ALGO POSTORDER (TREE *NODE) Step1: Step2: Step3: Step4: Step5: If (Node != Null). Print Node -> Data. Postorder (Node -> Right) [Function Called By Recursion.] Postorder (Node -> Left). [Function Called By Recursion]. Return.

34

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 

38.ALGORTHM FOR BREADTH FIRST SEARCH. (A) Algorithm: Following are the steps for breadth first search algorithm : (a) [Initialise the counter with zero for storing the arrival vertices of the graph] Set index = 0 (b) [Enter the vertices in the graph] Read(n_nodes) (c) [Initialise all vertices in the array with FALSE to indicate the absence of visits to the vertices] Repeat step (d) for(i=1;i<n_nodes;i++) (d) Set visited[i] = FALSE (e) [Read adjacent matrix of the graph, enter 1 in the array for all adjacent vertices j of vertex i and 0 for not] Repeat step (f) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (f) Read am[i][j] (g) [Check each vertex of the graph whether it is visited or not] Repeat step from (h) to (n) for(i=1;i<n_nodes;i++) (h) If(!visited(i)) then Call insert_queue(q, i) (i) [Check all the vertices adjacent to the vertex i] Repeat step from (j) to (n) while(front!=rear) (j) Set k = delete_queue(q) (k) Set visited[i] = TRUE 35

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
(l) [Check adjacent vertex of the graph whether it is visited or not] Repeat step from (m) to (n) for(j=1;j<n_nodes;j++) (m) If(am[i][j] == 0) then continue (n) [Check all the vertices adjacent to the vertex i] If(!visited(j)) then Set visited[j] = TRUE, Call insert_queue(q, j) (o) [Print the adjacent matrix of the graph] Repeat step (m) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (p) Write a[i][j] (q) [Print the sequence of traversal of a given graph] Repeat step (o) for(i=1;i<n_nodes;v++) (r) Write q[i] (s) End.

39. ALGORITHM FOR DEPTH FIRST SEARCH. (A) Algorithm : Following are the steps for depth first search : (a) [Initialise the counter with zero for storing the arrival vertices of the graph] Set index = 0 (b) [Enter the vertices in the graph] Read(n_nodes) (c) [Initialise all vertices in the array with FALSE to indicate the absence of visits to the vertices] Repeat step (d) for(i=1;i<n_nodes;i++) (d) Set visited[i] = FALSE (e) [Read adjacent matrix of the graph, enter 1 in the array for all adjacent vertices j of vertex i and 0 for not] Repeat step (f) for(i=1;i<n_nodes;v++), for(j=1;j<n_nodes;j++) (f) Read am[i][j] (g) [Check each vertex of the graph whether it is visited or not] Repeat step from (h) for(i=1;i<n_nodes;i++) (h) If(!visited(i)) then Call function visit(g,i) (i) [Print the adjacent matrix of the graph] Repeat step (m) for(i=1;i<n_nodes;v++), 36

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
for(j=1;j<n_nodes;j++) (j) Write a[i][j] (k) [Print the sequence of traversal of a given graph]
Repeat step (o) for(i=1;i<n_nodes;v++)

(l) Write nodes[i] (m) [Definition of the function DFS] void visit(g, i) (n) Set visited[i] = TRUE Set nodes[++index] = i (o) [Check all the vertices adjacent to the vertex i] Repeat step (p) for(j=1;j<n_nodes;j++) (p) If(am[i][j] == 1) then If(!visited(j)) then Call visit(g, j) recursively (q) End.

40 ALGORITHM TO COMPUTE SHORTEST PATH USING DIJKESTRAS TECHNIQUE. (Shortest-Path Algorithm) A weighted graph G with M nodes is maintained in memory by its weight matrix W. This algorithm finds a matrix Q such that Q[I,J] is the length of a shortest path from node VI to node VJ. INFINITY is a very large number, and MIN is the minimum value function. Step1> Repeat For I,J=1,2,….,M.[Initializes Q.] If W[I,J]=0, Then: Set Q[I,J]=INFINITY. Else Set Q[I,J]=W[I,J]. [End Of Loop] Repeat Steps 3 And 4 For K=1,2,…,M.[Updates Q] Repeat Step 4 For I=1,2,…,M. Repeat For J=1,2,..,M. Set Q[I,J]=MIN(Q[I,J],Q[I,K]+Q[K,J.) [End Of Loop.] [End Of Step 3 Loop.] [End Of Step 3 Loop.] [End Of Step 2 Loop.]

Step2> Step3> Step4>

37

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step5> Exit.

.

41(A) Algorithm : Following are the steps for prim’s algorithm. (a) [Read the vertices in the graph] Read(n_nodes) (b) [Read adjacent matrix of the graph. The weight will be taken infinity, if there is no direct path between one vertex to another vertex, we have used 1500 for infinity, enter cost 0 for vertex to itself] Repeat step (c) for(i=0;i<n_nodes;v++), for(j=0;j<n_nodes;j++) (c) Read adj_matrix[i][j] (d) [Write the adjacent matrix of the graph] Repeat for(i=0;i<n_nodes;i++) Repeat for(j=0;j<n_nodes;j++) Print(adj_matrix[i][j]) (e) [Initially none of the vertices are selected] for(i=0;i<n_nodes;i++) Set selected[i] = FALSE (f) [Initially enters 0 in the minimum spanning tree matrix] for(i=0;i<n_nodes;i++) for(j=0;j<n_nodes;j++)

38

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Set tree[i][j]=0 (g) [Select the vertex 0 as the starting vertex] Set selected[0]=TRUE, path[0]=0, length = 1 (h) [Find the nearest neighbour vertex of one of selected vertices]
Repeat step (i) to (n) while(length<=n_nodes)

(i) Set min = INFINITY (j) Repeat step(k) to (m)for(i=0;i<n_nodes;i++) (k) If(selected[i]==TRUE) then
(l) Repeat step(m) for(j=0;j<n_nodes;j++)

(m) If(selected[j]==FALSE) then
If(adj_matrix[i][j] <min) then

Set min = adj_matrix[i][j], u = i, w = j, (n) [Include the nearest neighbour into the tree] Set tree[u][w] = 1, selected[w] = TRUE, path[++k] = w, length = length + 1 (o) [ Write the minimum spanning tree adjacency matrix] Repeat for(i=0;i<n_nodes;i++) Repeat for(j=0;j<n_nodes;j++) Print(tree[i][j]) (p) [Write the shortest path from the source to all vertices] Repeat for(i=0;i<k;i++) Print(path[i]) (q) End.

42. ALGORITHM FOR THE ADDITION ,SUBTRACT AND MULTIPLICATION MATRIX. Matrix[A[],B[].C[],D[],E[],N] Step 1: Set Sum = 0. Step 2: For I = 1 To N. Step 3: For J = 1 ToN. Step 4: C[I][J] = A[I][J] + B[I][J]. Step 5: D[I][J] = A[I][J] – B[I][J]. Step 6: For K = 1 To N. Step 7: Sum = Sum + A[I][K] * B[K][J]. [End Of Step 6 Loop.] Step 8: Set E[I][J] = Sum. [End Of Step 3 Loop.] [End Of Step 2 Loop.]

OF TWO

39

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step 9: Exit.

43.ALGORITHM FOR SPARSE MATRIX. SPARSEMATRIX( A , SPARSE , ROW , COL)

Remarks -: Algorithm for Sparse Matrix. A[ ROW, COL ] is an two dimensional array with Elements in it. SPARSE is also an two dimensional array in which the resultant Sparse Matrix is stored. Step (1) -: Set SPARSE [1] [1] := ROW and SPARSE [1] [2] := COL Step (2) -: Set k = 1 40

Sushma Jaiswal, Lecturer S.O.S. in computer Science,  2010  Pt. Ravishankar Shukla University,Raipur) 
Step (3) -: Repeat Step ( 4 ) and Step ( 5 ) For i := 1 to ROW Step (4) -: Repeat Step ( 5 ) For j := 1 to COL Step (5) -: if ( A [ i ] [ j ] ≠ 0) Step(5a) -: Set SPARSE [ k ] [ 1 ] := i Step(5b) -: Set SPARSE [ k ] [ 2 ] := j Step(5c) -: Set SPARSE [ k ] [ 3 ] := A [ i ] [ j ] Step(5d) -: k := k + 1 Step(6) -: Set SPARSE [ 1 ] [ 3 ] := k - 1 Step(7) -: Exit

41

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->