Prerequisite
Prerequisite
in Computer Science,
Pt. Ravishankar Shukla University,Raipur
1 PREREQUISITE
1.1 INTRODUCTION
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
Prerequisite 3
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 False
Condition
Statement1 Statement2
Fig. 1.2
(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 False
Condition
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
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
0 25
1 30
2 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
0 4
1 8
2 12
3 16
4 20
5 24
6 28
7 32
8 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
0 4 0 4
1 8 1 8
2 12 2 12
3 16 3 16
4 20 4 20
5 28 5 24
6 32 6 28
7 36 7 32
8 40 8 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
16 Data Structures
Prerequisite 17
18 Data Structures
Prerequisite 19
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
22 Data Structures
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
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
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
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
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
Prerequisite 37
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 impleme-
ntation 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
**
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
44 Data Structures
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
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
50 Data Structures
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
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
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.
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
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
60 Data Structures
/*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
64 Data Structures
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
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
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
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
74 Data Structures
76 Data Structures
/*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
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
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
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
(*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
88 Data Structures
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
92 Data Structures
94 Data Structures
i j ROWLINK
INFO
COLUMNLINK
Fig. 2.7 Structure of a Node to Represent Sparse Matrix
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
1 0 0 3 0
2 0 5 0 0
3 0 0 0 2
4 1 0 0 4
5 0 0 0 0
6 0 0 7 0
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
ROH1
1 0 1 3
3
ROH2
2 0 2 2
5
ROH3
3 0 3 4
2
ROH4
4 0 4 1 4 4
1 4
ROH5
5 0
ROH6
6 0 6 3
7
96 Data Structures
9
9 8
7
STACKSIZE 6
5 UJJAIN
4 JABALPUR
5 3 INDORE
2 BHOPAL
TOP 1 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
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
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
/*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
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
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
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
{
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
{
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
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
Examples
AB+ CD- EF* 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
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
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
}
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
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);
default : if(isalpha(q[m]))
{
printf("%c",q[m]);
++m;
break;
}
else
{
printf("error");
exit(0);
}
}
}
}
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
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
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
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
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 result of the postfix
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 + -.
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
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
factorial( n ) = 1 if ( n = 0 )
n * factorial( n-1 ) if (n > 0)
0 if ( n = 0 )
fib( n ) = 1 if ( n = 1 )
fib( n-1 ) + fib( n-2 ) if (n >= 2)
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
GCD(m,n) If (n < m)
GCD(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));
}
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
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
Empty
Front Rear
12
Insert 12
Front Rear
12 23
Insert 23
Front Rear
12 23 34
Insert 34
Front Rear
23 34
Delete 12
Front Rear
23 34 45
Insert 45
Front Rear
23 34 45 56
Insert 56
Front Rear
Fig. 2.14 Array Representation of Queue
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
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
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
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
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
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
Empty
Front Rear
12
Insert 12
Front Rear
12 23
Insert 23
Front Rear
12 23 34
Insert 34
Front Rear
12 23 34 45
Insert 45
Front Rear
23 34 45
Delete 12
Front Rear
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
34 45
Delete 23
Front Rear
34 45 56
Insert 56
Front Rear
67 34 45 56
Insert 67
Rear Front
67 78 34 45 56
Insert 78
Rear Front
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 Front
Fig. 2.18
(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
Rear Front
Fig. 2.19
(iv) When the array is full the rear index will be exactly one
position before the front index.
Rear Front
Fig. 2.20
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
{
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
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
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
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
}
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
Front Rear
Fig. 2.21 Deque
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
Front Rear
Fig. 2.22 Input Restricted Deque
(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 Rear
Fig. 2.23 Output Restricted Deque
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
{
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
{
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
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
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
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
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
FM1 2
FM2 2
…
FMj-1 2 FMj-1
CS1 3
CS2 3
…
CSk-1 3 CSk-1
GU1 4
GU2 4
…
GUl-1
GUl-1 4
Fig. 2.24 Priority Queue Job Waiting for Printer
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur 2010
1 if n=0 or n=1
fact(n) =
n*fact(n-1) if n>1
(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 equiva-
lent 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
**
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
2010
3 TREES
3.1 INTRODUCTION
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
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 sub-
trees 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 8 9
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
C D
E F H I
K L
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
8 9 10 11 12 3
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 repres-
ented 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
C D
E F H I
K L
30 70
20 55 65 75
18 26 35 57 62
Level 1 2 C 3 D
E F H I
Level 2 4 5 6 7
K L
Level 3 8 9
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 . .
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.
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 F 4 7
2
3 B 0 0
4 C 3 6
5
6 D 0 0
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
2010
7 J 9 11
8
9 H 0 10
10 I 0 0
11 K 0 0
Trees 197
C J
B D H K
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
(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
(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
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
ROOT 60
30 35 65
20 55
18 26 35 57
38
ROOT 60
35 70
20 55 65
18 26 38 57
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
{
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
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
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
- *
B C / D
E F
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
e c
f h d
g i j
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
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 F G H I J
⋅05
⋅20 ⋅16 ⋅12 ⋅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
⋅10
⋅20 ⋅16 ⋅12 ⋅08 ⋅06 ⋅18 ⋅10
H
⋅05
⋅05
B E
⋅03 ⋅02
Fig. 3.26(c)
A C D I J
⋅10 ⋅14
⋅20 ⋅16 ⋅12 ⋅18 ⋅10
H
⋅05 F G
B E
⋅03 ⋅02
Fig. 3.26(d)
A C D I
⋅10 J F G
H
⋅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 ⋅26
⋅20 ⋅16 ⋅18
⋅10 J D
⋅14
⋅10 ⋅12
H
⋅05 F G
B E
⋅03 ⋅02
Fig. 3.26(f)
A
⋅34 ⋅20 ⋅26
⋅20
C I
⋅10 J D
⋅14
⋅16 ⋅18 ⋅10 ⋅12
H
⋅05 F G
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
C I A
⋅20 D
⋅14
⋅16 ⋅18 ⋅20 ⋅12
⋅10 J F G
H
⋅05
⋅05
B E
⋅03 ⋅02
Fig. 3.26(h)
⋅40 ⋅60
A
⋅20 ⋅34 ⋅26
⋅20
⋅10 J
C I D
⋅14
⋅10
⋅16 ⋅18 ⋅12
H
⋅05
⋅05 F G
B E ⋅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.
⋅40 ⋅60
A
⋅20 ⋅34 ⋅26
⋅20
⋅10 J
C I D ⋅14
⋅10
⋅16 ⋅18 ⋅12
H
⋅05
F G
⋅05
⋅08 ⋅06
B E
⋅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
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
{
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
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
TABLE 3.3
Range List Position Result New range
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("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
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
f(n)
log(n)
F DEPTH 1
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
2010
C DEPTH 2
J
B D DEPTH 3
F
DEPTH 1
C DEPTH 2
B
DEPTH 3
Fig. 3.28(b) Height Unbalanced Tree
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
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 =+∞.
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 kd
T1 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
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
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] 89 89
[1] 48
[2]
[3]
[4]
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 cluste-
red 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
[0] 89 89
[1]
[2] 48
[3]
[4]
[5]
[6]
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
{
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
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
Q.13. Give the pre order, inorder, post order, and level-order traversals
for the following trees :
S C
S O F T
Q H M D I L ?
E I U
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 SORTING ALGORITHMS
4.1 INTRODUCTION
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
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
Pass number 4
0 77 94 113 113 15 234 13 135 300 404 900
0 77 94 113 113 15 234 13 135 300 404 900
0 77 94 113 113 15 234 13 135 300 404 900
0 77 94 113 113 15 234 13 135 300 404 900
0 77 94 113 15 113 234 13 135 300 404 900
0 77 94 113 15 113 234 13 135 300 404 900
0 77 94 113 15 113 13 234 135 300 404 900
0 77 94 113 15 113 13 135 234 300 404 900
Swaps on this pass = 3
Pass number 5
0 77 94 113 15 113 13 135 234 300 404 900
0 77 94 113 15 113 13 135 234 300 404 900
0 77 94 113 15 113 13 135 234 300 404 900
0 77 94 15 113 113 13 135 234 300 404 900
0 77 94 15 113 113 13 135 234 300 404 900
0 77 94 15 113 13 113 135 234 300 404 900
0 77 94 15 113 13 113 135 234 300 404 900
Swaps on this pass = 2
Pass number 6
0 77 94 15 113 13 113 135 234 300 404 900
0 77 94 15 113 13 113 135 234 300 404 900
0 77 15 94 113 13 113 135 234 300 404 900
0 77 15 94 113 13 113 135 234 300 404 900
0 77 15 94 13 113 113 135 234 300 404 900
0 77 15 94 13 113 113 135 234 300 404 900
Swaps on this pass = 2
Pass number 7
0 77 15 94 13 113 113 135 234 300 404 900
0 15 77 94 13 113 113 135 234 300 404 900
0 15 77 94 13 113 113 135 234 300 404 900
0 15 77 13 94 113 113 135 234 300 404 900
0 15 77 13 94 113 113 135 234 300 404 900
Swaps on this pass = 2
Pass number 8
0 15 77 13 94 113 113 135 234 300 404 900
0 15 77 13 94 113 113 135 234 300 404 900
0 15 13 77 94 113 113 135 234 300 404 900
0 15 13 77 94 113 113 135 234 300 404 900
Swaps on this pass = 1
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
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
#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
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
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 :
16 7 9 5 2 18 8 53 1 44 17
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:
16 7 9 5 2 1 8 53 18 44 17
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) :
16 7 9 5 2 1 8 53 18 44 17
2 7 1 5 8 9 16 53 18 44 17
Repeat for the left sub-list of the 8, to obtain :
2 7 1 5 8 9 16 53 18 44 17
2 1 7 5 8 9 16 53 18 44 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
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 2 5 7 8 9 16 17 18 44 53
1 2 5 7 8 9 16 17 18 44 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 sub-
list 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
(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
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
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
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
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
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
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
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 19 22 11
10 Fig. 4.1
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
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 10 17 11
34 Fig. 4.4
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
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 10 11 33
34
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 10 22 33
34
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
17
12 10
11 19 22 33
34
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 19 22 33
34
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 19 22 33
34 Fig. 4.9
Sushma Jaiswal,Lecturer S.O.S. in Computer Science,
Pt. Ravishankar Shukla University,Raipur
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 19 22 33
34
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
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
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
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
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 GRAPHS
5.1 INTRODUCTION
This chapter covers graphs, along with their related definitions like-
definition 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 4
Graphs 283
1 3
2 4
Fig. 5.2
1 3
2 4
1 3
2 4
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->2
1,3 1->2->4->3
1,4 1->2->4
1,5 1->5
2,1 2->4->3->1
2,3 2->4->3
2,4 2->4
2,5 2->4->3->5
3,1 3->1
3,2 3->2
3,4 3->2->4
3,5 3->5
4,1 4->3->1
4,2 4->3->2
4,3 4->3
4,5 4->3->5
5,1 5->1
5,2 5->1->2
5,3 5->1->2->4->3
5,4 5->1->2->4
Sushma Jaiswal,Lecturer S.O.S. in Computer
Science, Pt. Ravishankar Shukla University,Raipur
[2010]
3 1
4 2
1 3
2 4
2 3 5 6
Graphs 287
5 6
1 4
7 2 3 5 6
8 9 10
1 3
2 4
Fig. 5.10
Table 5.4 Adjacency Matrix
Vertex 1 2 3 4 5
1 0 1 1 0 1
2 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
2 4
Fig. 5.11
Sushma Jaiswal,Lecturer S.O.S. in Computer
Science, Pt. Ravishankar Shukla University,Raipur
[2010]
Graphs 289
1 0 1 1 0 0
2 0 0 1 1 0
3 0 0 0 1 1
4 0 0 0 0 1
5 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 2-
dimensional 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.
6
3
2
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]
1 → 2 → 3 → 4
2 → 3
3 → 4
4 → 5 → 6
5 → 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 3
5
4 3 4 5
2 5
2 4
Figure 5.14
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 v5
v1 v6
v3 v4
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 v2, v3 v2
v1, v2 v1, v3 , v4, v5 v3
v1, v2 , v3 v1, v2 , v4, v5 v4
v1, v2 , v3, v4 v2, v3 , v5, v6 v5
v1, v2 , v3, v4 ,v5 v2, v3 , v4, v6 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]
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]
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]
Graphs 299
v1 v2
v5
v3 v4
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]
Graphs 303
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]
}
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
!!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 v4
Fig. 5.17
Spanning Trees:
v1 v2 v1 v2
v3 v4 v3 v4
v1 v2 v1 v2
v3 v4 v3 v4
Fig. 5.18
Sushma Jaiswal,Lecturer S.O.S. in Computer
Science, Pt. Ravishankar Shukla University,Raipur
[2010]
Graphs 309
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
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]
Source Graph
Adjacency Matrix
0
2 5
0 1 2 3 4
6 3 0 - 5 3 - 2
4 1
10 6 1 5 - 1 6 6
4 1 2 3 1 - 2 10
3 - 6 2 - 4
3 2 2
4 2 6 10 4 -
Initial Tree 0
4 1
We start with source node 0.
3 2
Graphs 315
Final stage
Now we have 3 (as adjacent vertices of
0 1) 3 (as remaining adjacent vertex of 2)
2
and 3 (as remaining adjacent vertex of
3 4).
4 1 Now we again compare the length of the
paths from source vertex to these
1 unattached vertices, We find the
length(23)=2 is the minimum. Therefore,
3 2 we choose vertex 3. The total length of
2 the tree can be calculated as 8.
Fig. 5.19
(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]
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]
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
v1 v6
v3 v4
Fig. 5.21
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 v5
v1 1 v6
1
v3 v4
Fig. 5.22
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 v5
v1 1 2 v6
2 1
v3 v4
Fig. 5.23
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 v5
3
v1 1 2 v6
2 1
v3 v4
Fig. 5.24
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
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]
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 5
3 2
2
0
2 5 Choose the closest node to 0.
We locate the vertex closest to it, i.e., we
4 1 find a vertex from the adjacent vertices of
3
D=2 D=5 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
Graphs 325
/*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]
Graphs 329
v2 v5
v8
v4
v1 v3 v7
v6
v2 v6
v1 v3 v7 v9
v8
v4 v5
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 7 6 7 2
3
A E G J L
4 7 4 3 4 5
F I K
2 6
Sushma Jaiswal,Lecturer S.O.S. in Computer
Science, Pt. Ravishankar Shukla University,Raipur
[2010]
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 F H
1 3 3 7
E 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 v5
v1 v6
v3 v4
**
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
This algorithm traverses a linear array LA with lower bound LB and upper bound UB.
1
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
2
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
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.
3
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
[This algorithm traverses a two dimensional array TD with lower bound LB and upper
bound UB.]
4
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
5
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
(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)
POLISH (Q,P)
Suppose Q Is An Arithmetic Expression Written In Infix Notation. This
Algorithm Finds The Equivalent Postfix Expression P.
Step1: Push “(” onto STACK, And Add “)” To The End Of Q.
Step2: Scan Q From Left To Right And Repeat Step3 To 6 For Each
Element Of Q Until The Stack Is Empty.
Step3: If An Operand Is Encounter, Put It On Stack.
Step4: 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.]
Step5: Set VALUE Equal To The Top Element On Stack.
Step6: Exit.
7
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
8
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
9
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
10
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Remarks-: Algorithm for Tower of Hanoi. This procedure gives a recursive solution to
the Tower of Hanoi problem for N disks.
[ End of If Structure ]
Step(2)-: IF N = 1, then :
Step(3)-: ELSE
Step(4)-: Call TOWER( N-1, BEG, END, AUX ) [ Move N-1 Disk peg BEG to
peg AUX ]
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
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This Procedure Insert An Element Item Into Queue.
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This Procedure delet An Element Item Into Queue.
12
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
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;
Add at REAR Operation:- This operation add an element at the rear of the deque.
Delete From FRONT Operation:- This Operation Deletes Or Remove The Item From the
Front Of The Deque.
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.]
Step2> [Check for Empty Deque.]
If FRONT=REAR. Then:
Set FRONT=0 And REAR=0.
[End Of If Structure.]
Step3> [Return ITEM from the FRONT of the Deque.]
Return ITEM.
Step4> Exit.
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.
15
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Step4> Exit.
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)
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)
19
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
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.
20
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
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)
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)
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)
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. ]
[ End of If Structure ]
23
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
24
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
25
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Remark-: Algorithm for sorting numbers through Selection Sort. A is an array with N
elements. This algorithm sorts numbers in array A.
[End of loop]
Step(4)-: Exit
26
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
27
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
SHLSORT([20],FLAG ,I,J,G,N,T)
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
(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)
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)
30
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Procedure:-DELHEAP(TREE,N,ITEM)
31
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
32
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Step 7: Return(T).
Step 8: Return.
33
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
34
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
(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)
(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.
37
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Step5> Exit.
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.
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.]
39
Sushma Jaiswal, Lecturer S.O.S. in computer Science, 2010
Pt. Ravishankar Shukla University,Raipur)
Step 9: Exit.
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)
41