Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
1. DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
LAB MANUAL
DATA STRUCTURES
CS-305
List of Experiments
S# Name of Experiment Page#
1 Program to input marks of 5 subjects and print the total and percentage using arrays
2 Program to find highest and lowest element in an array
3 Program to find the sum of even and odd elements in an array
4 Program to read two 3x3 matrices and add them
5 Program to find whether a matrix is upper triangular or not
6 Program to read two matrices and multiply them
7 Program to find the factorial of a number using recursion
8 Program to generate the Fibonacci series using recursion
9 Program to perform the following string operations:
a) Find length of entered string
b) Concatenate two strings
c) Copy one string to another
d) Compare two strings
e) Reverse the entered string
2. f) Check whether the entered string is a palindrome
10 Program to create a stack and implement push and pop operations on it
11 Program to implement multiple stack
12 Program to create a queue and implement insertion and deletion operations on it
13 Program to create a circular queue and implement insertion and deletion operations
on it
14 Program to create a linked list and implement insertion and deletion operations on it
15 Program to implement the solution to Josephus Problem using doubly circular liked
list
16 Program to traverse a binary tree in pre-order, in-order and post-order
17 Program to implement binary search
18 Program to implement binary search tree
19 Program to implement sorting of data using:
a)Bubble sort
b) Selection sort
c) Insertion sort
d) Quick sort
e) Merge sort
f) Heap sort
20 Program to implement a graph and traverse it using Breadth First Search
3. EXPERIMENT NO.1
AIM:
Program to input marks of 5 subjects and print the total and percentage using arrays
INTRODUCTION:
An array is a linear data structure that stores homogeneous data in contiguous memory
locations. In this experiment the user will input marks in 5 subjects which will be stored in an
array of size 5. The data in the array will then be added to find the total marks and percentage
will be calculated out of 500.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void main()
{
float marks[5],total=0,per;
clrscr();
//Asking for marks from user and adding it to total
for(int i=0;i<=4;i++)
{
cout<<"Enter marks in subject "<<i+1<<":";
cin>>marks[i];
total=total+marks[i];
}
//Calculation of percentage and printing
per=total/5;
cout<<"nTotal="<<total<<" out of 500nPercentage="<<per<<"%";
getch();
}
SAMPLE OUTPUT:
Enter marks in Subject 1:90
Enter marks in Subject 2:90
Enter marks in Subject 3:90
4. Enter marks in Subject 4:90
Enter marks in Subject 5:90
Total=450 out of 500
Percentage=90%
QUESTIONS
What is an array?
What is the limitation of array?
What is bound Checking?
Difference between array & structure?
What is Type Conversion?
EXPERIMENT NO.2
AIM:
Program to find highest and lowest element in an array
INTRODUCTION:
The user will be required to enter the elements in an array. Variables min and max would be
set to the first element of the array. The program will then scan all the elements in the array
and set the values of min and max variables depending upon the condition.
SOURCE CODE:
#include<iostream.h>
5. #include<conio.h>
void main()
{ int a[5],min,max;
clrscr();
for(int i=0;i<=4;i++)
{ cout<<"Enter a number:";
cin>>a[i];
}
min=max=a[0]; //min and max values intialized to first array value
for(i=1;i<=4;i++)
{ if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
cout<<"nMaximum="<<max<<"nMinimum="<<min;
getch();
}
SAMPLE OUTPUT:
Enter a number:0
Enter a number:5
Enter a number:7
Enter a number:9
Enter a number:8
Maximum=9
Minimum=0
Questions
Q.1 How to find min, max element in array?
Q.2What is the basic requirement of finding the minimum element in an array?
Q.3 In how many ways you can find the maximum and minimum elements in an array?
Q.4 How many variables minimumly required in minmax algorithm?
6. EXPERIMENT NO.3
AIM:
Program to find the sum of even and odd elements in an array
INTRODUCTION:
The user will be required to input the elements in the array. The program will then scan the
elements in the array and check whether the number is odd or even. The mod operator (%)
would be used to check the divisibility of numbers by 2. If number mod 2 is 0 then the
number is even and it would be added to the sum of even numbers else it would be added to
the sum of odd numbers.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void main()
{ int a[5],i,n,sum_e=0,sum_o=0;
clrscr();
for(i=0;i<=4;i++)
{ cout<<"Enter element:";
cin>>a[i];
}
for(i=0;i<=4;i++)
{ if(a[i]%2==0) //Check for even number
sum_e+=a[i];
else
sum_o+=a[i];
}
cout<<"nSum of even numbers="<<sum_e;
cout<<"nSum of odd numbers="<<sum_o;
getch();
}
SAMPLE OUTPUT:
Enter element:2
Enter element:3
Enter element:2
Enter element:3
Enter element:2
Sum of even numbers=6
7. Sum of odd numbers=6
Questions
Q.1 What is the use of mod function in finding even and odd numbers?
Q.2 What role does the mod play when a number is reversed from its actual form?
Q.3 How many comparisons does the program required for finding the number to be odd or
even?
Q.4 What is the use of “+=” operator in the above program ?
EXPERIMENT NO.4
AIM:
Program to read two 3x3 matrices and add them
INTRODUCTION:
The user will be required to input the elements in the 3x3 matrices A and B. The elements of
the matrices would be added and stored in matrix C. Nested for loops would be used for
entering elements into the matrices and to calculate the sum matrix.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
8. cout<<"MATRIX An";
//Matrix values to be entered by user
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<"nEnter element:";
cin>>a[i][j];
}
}
cout<<"nMATRIX Bn";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<"nEnter element:";
cin>>b[i][j];
}
}
//Addition of two matrices
cout<<"nMATRIX C=MATRIX A+MATRIX Bn";
for(i=0;i<=2;i++)
{ cout<<"nn";
for(int j=0;j<=2;j++)
{
c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j]<<"t";
}
}
getch();
}
SAMPLE OUTPUT:
MATRIX A:
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
MATRIX B:
Enter element:2
Enter element:2
Enter element:2
9. Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
Enter element:2
MATRIX C=MATRIX A+MATRIX B
4 4 4
4 4 4
4 4 4
Questions
Q.1 What is the first condition to be checked when two matrixs are added?
Q.2 Why double dimensional array is used for matrix representations as well as operations?
Q.3 What is the importance of the operator “n” and ”t” for the above program?
EXPERIMENT NO.5
AIM:
10. Program to find whether a matrix is upper triangular or not
INTRODUCTION:
In an nxn matrix, if all elements below the diagonal are 0, then it is called an upper
triangular matrix. Similarly, in an nxn matrix, if all elements above the diagonal are 0, then
it is called a lower triangular matrix.
Example:
2 2 2 3 0 0
0 3 3 5 3 0
0 0 5 2 4 5
Upper Triangular Matrix Lower Triangular Matrix
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],i,j,n,flag;
clrscr();
cout<<"Enter order of the matrix:";
cin>>n;
//Matrix values to be entered by the user
cout<<"nEnter matrix elements:n";
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
cout<<"a["<<i<<"]["<<j<<"]=";
cin>>a[i][j];
}
}
//Check for upper triangular matrix
flag=1;
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j][i]!=0)
{
flag=0;
break;
}
}
}
if(flag)
cout<<"Upper Triangular Matrix";
else
cout<<"Not an Upper Triangular Matrix";
getch();
}
11. SAMPLE OUTPUT 1:
Enter order of the matrix:3
Enter matrix elements:
a[0][0]=2
a[0][1]=2
a[0][2]=2
a[1][0]=2
a[1][1]=2
a[1][2]=2
a[2][0]=2
a[2][1]=2
a[2][2]=2
Not an Upper Triangular Matrix
SAMPLE OUTPUT 2:
Enter order of the matrix:3
Enter matrix elements:
a[0][0]=2
a[0][1]=2
a[0][2]=2
a[1][0]=0
a[1][1]=2
a[1][2]=2
a[2][0]=0
a[2][1]=0
a[2][2]=2
Upper Triangular Matrix
Questions
Q.1 What is Upper triangular matrix?
12. Q.2 What is linear and non linear data structure?
Q.3 Example of linear data structure?
Q.4 How does matrix represented?
EXPERIMENT NO.6
AIM:
Program to read two matrices and multiply them
INTRODUCTION:
The user will first enter the number of rows and columns of the two matrices. The
multiplication of matrices is possible only if the number of columns in the first matrix is
equal to the number of rows of the second matrix. If multiplication is possible, user will enter
the values in both matrices. The program logic of matrix multiplication is applied to get the
resultant matrix.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
int i,j,k,m,n,p,q,a[5][5],b[5][5],c[10][10];
cout<<"n Enter the number of rows in 1st matrix: ";
cin>>m;
cout<<"n Enter the number of columns in 1st matrix: ";
cin>>n;
cout<<"n Enter the number of rows in 2nd matrix: ";
cin>>p;
cout<<"n Enter the number of columns in 2nd matrix: ";
cin>>q;
//Check for possibility of matrix multiplication
if(n==p)
cout<<"n Matrix multiplication possible";
else
{
cout<<"n Matrix multiplication not possible";
getch();
exit(0);
13. }
//Matrix values to be entered by user
cout<<"nn Enter the 1st matrix:n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>a[i][j];
}
cout<<"nn Enter The 2nd matrix:n";
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
cin>>b[i][j];
}
//Display matrices
cout<<"nn The 1st matrix:n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<a[i][j]<<"t";
cout<<"n";
}
cout<<"nn The 2nd matrix:n";
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
cout<<b[i][j]<<"t";
cout<<"n";
}
//Matrix multiplication
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
//Display resultant matrix
cout<<"nn The Resultant matrix:n";
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
cout<<c[i][j]<<"t";
cout<<"n";
}
getch();
}
SAMPLE OUTPUT:
Enter the number of rows in 1st matrix:3
Enter the number of columns in 1st matrix:2
Enter the number of rows in 2nd matrix:2
14. Enter the number of columns in 2nd matrix:3
Matrix multiplication possible
Enter the 1st matrix:
2
3
4
5
6
7
Enter the 2nd matrix:
2
3
4
5
6
7
The 1st matrix:
3
5
7
The 2nd matrix:
2 3 4
5 6 7
The Resultant matrix:
19 24 29
33 42 51
47 60 73
Questions
15. Q.1. What is matrix multiplication condition?
Q.2. How does the loop works in matrix multiplication?
Q.3 How does the resulting matrix size is decided?
EXPERIMENT NO.7
AIM:
Program to find the factorial of a number using recursion
INTRODUCTION:
A factorial of a number n is the continued product n x (n-1) x (n-2)……..x 1
Recursively it could be written as
n!=n x (n-1)!
=n x (n-1) x (n-2)!
……….
= n x (n-1) x (n-2) x…………x 1!
Functions which call themselves repeatedly until a certain condition is met, are called
recursive functions.
SOURCE CODE:
#include<iostream.h>
16. #include<conio.h>
int fact(int);
void main()
{ int n,ans;
clrscr();
cout<<"Enter any number:";
cin>>n;
ans=fact(n); //Calling recursive function fact(int)
cout<<"nFactorial of "<<n<<"="<<ans;
getch();
}
int fact(int x) //Recursive function body
{ int y;
if(x==0)
return(1);
y=fact(x-1);
return(x*y);
}
SAMPLE OUTPUT:
Enter any number: 5
Factorial of 5=120
Questions
Q.1 What is recursion?
Q.2 What is the benefit of using recursion in programming?
Q.3 Does every algorithm has its recursive solution? How and why?
EXPERIMENT NO.8
AIM:
Program to generate the Fibonacci series using recursion
INTRODUCTION:
Fibonacci Series is a series that starts with 0 and 1. Every next number in the series will be
the sum of the previous two numbers. Hence, the series would be
0 1 1 2 3 5 8 13 and so on.
In this program the user will give the limit of the series, i.e. the number of terms in the series
and the recursive procedure will be executed to generate the series.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void fseries(int); //Function prototype
void main()
{
17. int limit,f0=0,f1=1;
clrscr();
cout<<"Enter limit of Fibonacci Series:";
cin>>limit;
cout<<"ntttFIBONACCI SERIESn";
if(limit>2)
{
cout<<f0<<"n"<<f1;
fseries(limit-2); //Calling recursive function
}
else if(limit==2)
cout<<f0<<"n"<<f1;
else if(limit==1)
cout<<f1;
else
cout<<"Series not possible";
getch();
}
void fseries(int p) //Recursive function body
{
int fib;
static int f0=0,f1=1;
if(p==0)
cout<<"nEnd of fibonacci series";
else
{
fib=f0+f1;
f0=f1;
f1=fib;
cout<<"n"<<fib;
fseries(p-1);
}
}
SAMPLE OUTPUT:
Enter limit of Fibonacci Series:10
FIBONACCI SERIES
0
1
1
2
3
5
8
13
21
18. 34
End of fibonacci series
Questions
Q.1 What is Fibonacci Series?
Q.2 Where does the series is used?
EXPERIMENT NO.9
AIM:
Program to perform the following string operations:
a) Find length of entered string
b) Concatenate two strings
c) Copy one string to another
d) Compare two strings
e) Reverse the entered string
f) Check whether the entered string is a palindrome
INTRODUCTION:
A string constant is a one dimensional array of characters terminated by a null (0) character.
A string can be initialized as follows:
char name[ ]=”ABC”;
A null character will be appended to the string while storing it in memory locations as shown
below:
A B C 0
Hence, null character will be used in string operations to check the end of the string.
SOURCE CODE:
Experiment 9 (a): Program to find the length of the string
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
19. char a[20];
int c=0,i=0;
clrscr();
cout<<"Enter any string: ";
gets(a);
while(a[i]!=NULL)
{
c++;
i++;
}
cout<<"nLength of string is "<<c;
getch();
}
SAMPLE OUTPUT:
Enter any string: ABC
Length of string is 3
Experiment 9 (b): Program to concatenate two strings
#include<iostream.h>
#include<conio.h>
void main()
{
char a[15],b[15],c[30]={'0'};
int i,j,k;
clrscr();
cout<<"Enter the first string:";
cin>>a;
cout<<"Enter the second string:";
cin>>b;
for(i=0;a[i]!=NULL;i++)
c[i]=a[i];
for(j=i,k=0;b[k]!=NULL;j++,k++)
c[j]=b[k];
cout<<"The concatenated string is "<<c;
getch();
}
SAMPLE OUTPUT:
Enter the first string:ABC
Enter the second string:DEF
The concatenated string is ABCDEF
Experiment 9 (c): Program to copy one string to another
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20],b[20]={'0'};
int i=0;
20. clrscr();
cout<<"Enter the string: ";
gets(a);
while(a[i]!=NULL)
{
b[i]=a[i];
i++;
}
cout<<"The entered string is "<<a;
cout<<"nThe copied string is "<<b;
getch();
}
SAMPLE OUTPUT:
Enter the string: ABC
The entered string is ABC
The copied string is ABC
Experiment 9 (d): Program to compare two strings
#include<iostream.h>
#include<conio.h>
void main()
{
char a[15],b[15];
int i,c=0;
clrscr();
cout<<"Enter the first string:";
cin>>a;
cout<<"Enter the second string:";
cin>>b;
for(i=0;a[i]!=NULL||b[i]!=NULL;i++)
{
if(a[i]!=b[i])
{
c=1;
break;
}
}
if(c==0)
cout<<"The entered strings are same";
else
cout<<"The entered strings are not same";
getch();
}
SAMPLE OUTPUT:
Enter the first string: ABC
Enter the second string: ABC
The entered strings are same
Experiment 9 (e): Program to reverse the entered string
21. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char a[20],b[20]={'0'};
int i,len,c=0;
clrscr();
cout<<"Enter any string:";
gets(a);
for(i=0;a[i]!='0';i++)
c++;
len=c;
for(i=0;i<=len-1;i++)
{
b[i]=a[c-1];
c--;
}
cout<<"Reversed String:";
for(i=0;b[i]!='0';i++)
cout<<b[i];
getch();
}
SAMPLE OUTPUT:
Enter any string:ABCDE
Reversed String:EDCBA
Experiment 9 (f): Program to check whether the entered string is a palindrome
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char a[20];
int i,len=0,flag=0;
clrscr();
cout<<"Enter any string:";
gets(a);
for(i=0;a[i]!='0';i++)
len++;
for(i=0;a[i]!='0';i++)
{
if(a[i]!=a[len-1])
flag=1;
len--;
}
if(flag)
cout<<"Entered string is not a palindrome";
else
cout<<"Entered string is a palindrome";
22. getch();
}
SAMPLE OUTPUT 1:
Enter any string: abcddcba
Entered string is a palindrome
SAMPLE OUTPUT 2:
Enter any string: abc
Entered string is not a palindrome
Questions
Q.1 What is a string?
Q.2 How you can differ a string and a character?
Q.3 How many functions exists for string operations?
Q.4 Which is the header file used for operating string?
Q.5 What is the use of gets() and puts() function in string?
Q.6 Why null symbol is used to stop the string?
Q.7 What is the ASCII value of null character?
Q.8 How could you find the length of string without using string function?
Q.9 What is palindrome?
Q.10 What is the use of ASCII value while checking the string is palindrome or not?
EXPERIMENT NO.10
AIM:
Program to create a stack and implement push and pop operations on it
INTRODUCTION:
A stack is a list of elements in which an element may be inserted or deleted only at one end,
called the top of the stack. It works on the principle of Last In First Out. The insertion
operation is termed as push and the deletion operation is termed as pop. In C/C++, array
indexing begins at 0. So, initially Top pointer is kept at -1.
Algorithm for push operation:
23. If Top=Maxsize-1
then print overflow and exit.
Set Top=Top+1
Set stack[Top]=Item
Exit
Algorithm for pop operation:
If Top<0
then print underflow and exit.
Item=stack[Top]
Set Top=Top-1
Return Item
Exit
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
#include<process.h>
#define MAX 10
void push(void);
int pop(void);
void traverse(void);
int stack[10];
int tos=-1;
void main()
{
clrscr();
char ch1='y';
int ch;
while(ch1=='y')
{
cout<<"ttttSTACK";
cout<<"n 1.PUSH";
cout<<"n 2.POP";
cout<<"n 3.TRAVERSE";
cout<<"n Enter your choice:";
cin>>ch;
switch(ch)
{
case 1: push();
break;
case 2: int p;
p=pop();
cout<<"n The popped element is "<<p;
break;
case 3: traverse();
break;
default: cout<<"n Wrong choice!!!!!!!!!! ";
24. }
cout<<"n Do you want to continue???? ";
cin>>ch1;
}
}
void push() //Function to push element
{
int item;
if(tos==MAX)
{
cout<<"n Stack full";
getch();
exit(0);
}
else
{
cout<<"n Enter element to push: ";
cin>>item;
tos=tos+1;
stack[tos]=item;
}
}
int pop() //Function to pop element
{
int item;
if(tos==-1)
{
cout<<"n Stack empty";
getch();
exit(0);
}
else
{
item=stack[tos];
tos=tos-1;
}
return(item);
}
void traverse() //Function to display stack elements
{
if(tos==-1)
{
cout<<"n Stack empty";
getch();
exit(0);
}
else
{
for(int i=tos; i>=0; i--)
cout<<stack[i]<<"t";
}
}
SAMPLE OUTPUT:
STACK
1.PUSH
2.POP
25. 3.TRAVERSE
Enter your choice:1
Enter element to push: 12
Do you want to continue???? y
STACK
1.PUSH
2.POP
3.TRAVERSE
Enter your choice:1
Enter element to push: 34
Do you want to continue???? y
STACK
1.PUSH
2.POP
3.TRAVERSE
Enter your choice:3
34 12
Do you want to continue???? y
STACK
1.PUSH
2.POP
3.TRAVERSE
Enter your choice:2
The popped element is 34
Do you want to continue???? y
STACK
1.PUSH
2.POP
3.TRAVERSE
26. Enter your choice:2
The popped element is 12
Do you want to continue???? y
STACK
1.PUSH
2.POP
3.TRAVERSE
Enter your choice:2
Stack empty
EXPERIMENT NO.11
AIM:
Program to implement multiple stack
INTRODUCTION:
In a multiple stack, more than one stack would be implemented in a single array. This
program implements two stacks, stack1 and stack2 on a single array. The top of stack1 (top1)
will be initialized to -1 and the top of stack2 (top2) will be initialized to max. Every push
operation in stack1 will increment top1 by 1 and every pop operation from stack1 will
decrement top1 by 1. Every push operation in stack2 will decrement top2 by 1 and every pop
operation from stack2 will increment top2 by 1.
Stack1
Stack2
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
#include<process.h>
#define max 5
int pop(int s);
void push(int i,int s);
28. if (s==2)
{
if(top2==max)
{
cout<<"n stack 2 empty";
getch();
exit(0);
}
else
{
c--;
return(st[top2++]);
}
}
return(0);
}
};
void main()
{
clrscr();
stack sk;
int ch,i,s;
char ch1='y';
while(ch1=='y')
{
cout<<"nntttt MULTIPLE STACKS";
cout<<"n 1.PUSH";
cout<<"n 2.POP";
cout<<"n Enter your choice: ";
cin>>ch;
switch(ch)
{
case 1: cout<<"n Enter The stack in which you want to push : ";
cin>>s;
cout<<"n Enter the number you want to push: ";
cin>>i;
sk.push(i,s);
break;
case 2: cout<<"n Enter the stack from which you want to pop : ";
cin>>s;
i=sk.pop(s);
cout<<"n The popped element is: "<<i;
break;
default: cout<<"n Wrong choice!!!!!";
}
cout<<"nn Do you want to continue???? ";
cin>>ch1;
}
getch();
}
SAMPLE OUTPUT:
MULTIPLE STACKS
1.PUSH
2.POP
29. Enter your choice: 1
Enter The stack in which you want to push : 1
Enter the number you want to push: 11
Do you want to continue???? y
MULTIPLE STACKS
1.PUSH
2.POP
Enter your choice: 1
Enter The stack in which you want to push : 2
Enter the number you want to push: 22
Do you want to continue???? y
MULTIPLE STACKS
1.PUSH
2.POP
Enter your choice: 2
Enter the stack from which you want to pop : 2
The popped element is: 22
Do you want to continue???? y
MULTIPLE STACKS
1.PUSH
2.POP
Enter your choice: 2
Enter the stack from which you want to pop : 1
The popped element is: 11
Do you want to continue???? y
MULTIPLE STACKS
1.PUSH
2.POP
Enter your choice: 2
30. Enter the stack from which you want to pop : 1
Both stacks empty
EXPERIMENT NO.12
AIM:
Program to create a queue and implement insertion and deletion operations on it
INTRODUCTION:
A queue is a linear data structure that works on the principle of First In First Out. The element
inserted first in the queue will be deleted first. Two variables front and rear would be implemented to
keep a track of the inserted and deleted items. Initially both front and rear will be at -1. With every
insertion rear will be incremented and with every deletion front will be incremented. Hence all
insertions would take place at the rear end and all deletions will take place at the front end.
For n=10
Condition for empty queue:
front=rear=-1
Queue after 2 insertions:
2 3
front=0 rear=1
Condition for queue full:
2 3 4 5 6 7 8 9 10 11
front=0
rear=9
Insertion Algorithm:
If rear=max-1 then print “Queue full” and exit.
Set rear=rear+1
Set queue[rear]=item
Exit
Deletion Algorithm:
If front=rear then print ”Queue empty” and exit
Set front=front+1
31. Return item=queue[front]
Exit
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
#include<process.h>
int queue[5];
long front,rear;
void initqueue();
void display();
void main()
{
int choice,info;
clrscr();
//Initialising queue
initqueue();
while(1)
{
//Displaying menu
printf("n MENU n");
printf("1.Insert an element in queuen");
printf("2.Delete an element from queuen");
printf("3.Display the queuen");
printf("4.Exit!n");
printf("Your choice: ");
scanf("%i",&choice);
switch(choice)
{
case 1: if(rear<4)
{
printf("enter the number");
scanf("%d",&info);
if (front==-1)
{
front=0;
rear=0;
}
else
rear=rear+1;
queue[rear]=info;
}
else
{
printf("queue is full");
getch();
}
break;
case 2: int info;
if(front!=-1)
{
info=queue[front];
if(front==rear)
32. {
front=-1;
rear=-1;
}
else
front=front+1;
printf("no deleted is = %d",info);
}
else
printf("queue is empty");
getch();
break;
case 3: display();
getch();
break;
case 4: exit(0);
break;
default:printf("You entered wrong choice!");
getch();
break;
}
}
}
void initqueue()
{
//Initialising front & rear to -1
front=rear=-1;
}
/*displays the current position of the queue*/
void display()
{
int i; //For loop driver
//Displaying elements in queue
for(i=front;i<=rear;i++)
printf("%in",queue[i]);
}
SAMPLE OUTPUT:
MENU
1.Insert an element in queue
2.Delete an element from queue
3.Display the queue
4.Exit!
Your choice: 1
enter the number12
MENU
1.Insert an element in queue
33. 2.Delete an element from queue
3.Display the queue
4.Exit!
Your choice: 1
enter the number45
MENU
1.Insert an element in queue
2.Delete an element from queue
3.Display the queue
4.Exit!
Your choice: 2
no deleted is = 12
MENU
1.Insert an element in queue
2.Delete an element from queue
3.Display the queue
4.Exit!
Your choice: 3
45
MENU
1.Insert an element in queue
2.Delete an element from queue
3.Display the queue
4.Exit!
Your choice: 4
EXPERIMENT NO.13
AIM:
Program to create a circular queue and implement insertion and deletion operations on it
INTRODUCTION:
34. A circular queue is a queue in which the link of the last element points back to the first element.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
#define MAXSIZE 5
int cq[10];
int front=-1,rear=0;
void cqinsert();
int cqdelete();
void cqdisplay();
int choice;
char ch;
void main()
{
clrscr();
do
{ printf("--------1. Insert---------n");
printf("------- 2. Delete---------n");
printf("------- 3. Display--------n");
printf("------- 4. Exit------------n");
printf("Enter your choicen");
scanf("%d",&choice);
switch(choice)
{
case 1 : cqinsert();
break;
case 2 : cqdelete();
break;
case 3 : cqdisplay();
break;
case 4: return;
}
fflush(stdin);
}
while(choice!=4);
}
void cqinsert() //Function to insert element
{
int num;
if(front==(rear+1)%MAXSIZE)
{
printf("Queue is fulln");
return;
}
else
{
printf("Enter the element to be insertedn");
scanf("%d",&num);
if(front==-1)
front=rear=0;
else
rear=(rear+1) % MAXSIZE;
cq[rear]= num;
}
return;
35. }
int cqdelete() //Function to delete element
{
int num;
if(front==-1)
{
printf("Queue is Emptyn");
return 0;
}
else
{
num=cq[front];
printf("Deleted element is =%dn",cq[front]);
if(front==rear)
front=rear=-1;
else
front=(front+1)%MAXSIZE;
}
return(num);
}
void cqdisplay() //Function to display queue elements
{
int i;
if(front==-1)
{
printf("Queue is emptyn");
return;
}
else
{
printf("nThe status of the queuen");
for(i=front;i<=rear;i++)
{
printf("%dn",cq[i]);
}
}
if(front>rear)
{
for(i=front;i<MAXSIZE;i++)
{
printf("%dn",cq[i]);
}
for(i=0;i<=rear;i++)
{
printf("%dn",cq[i]);
}
}
printf("n");
}
SAMPLE OUTPUT:
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
------- 4. Exit------------
Enter your choice
36. 1
Enter the element to be inserted
12
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
------- 4. Exit------------
Enter your choice
1
Enter the element to be inserted
34
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
------- 4. Exit------------
Enter your choice
2
Deleted element is =12
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
------- 4. Exit------------
Enter your choice
1
Enter the element to be inserted
34
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
37. ------- 4. Exit------------
Enter your choice
3
The status of the queue
34
34
--------1. Insert---------
------- 2. Delete---------
------- 3. Display--------
------- 4. Exit------------
Enter your choice
4
EXPERIMENT NO.14
AIM:
Program to create a linked list and implement insertion and deletion operations on it
INTRODUCTION:
Linked lists are list of data elements linked to one another. The logical ordering is represented
by having each element pointing to the next element. Each element is called a node, which
has two parts:
38. info part which stores the information
next part which points to the next element
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int info;
struct node *next;
};
typedef struct node NODE;
NODE *start;
void traversinorder(NODE *start)
{
while(start != (NODE *) NULL)
{
printf("%dn",start->info);
start=start->next;
}
}
void insertatbegin(int item)
{
NODE *ptr;
ptr=(NODE *)malloc(sizeof(NODE));
ptr->info=item;
if(start==(NODE *)NULL)
ptr->next=(NODE *)NULL;
else
ptr->next=start;
start=ptr;
}
void insert_at_end(int item)
{
NODE *ptr,*loc;
ptr=(NODE *)malloc(sizeof(NODE));
ptr->info=item;
ptr->next=(NODE *)NULL;
if(start==(NODE*)NULL)
start=ptr;
else
{
loc=start;
while(loc->next!=(NODE *)NULL)
loc=loc->next;
loc->next=ptr;
}
}
void dele_beg(void)
{
NODE *ptr;
if(start==(NODE *)NULL)
return;
else
39. {
ptr=start;
start=(start)->next;
free(ptr);
}
}
void dele_end(NODE *start)
{
NODE *ptr,*loc;
if(start==(NODE *)NULL)
return;
else if((start)->next==(NODE *)NULL)
{
ptr=start;
start=(NODE *)NULL;
free(ptr);
}
else
{
loc=start;
ptr=(start)->next;
while(ptr->next!=(NODE *)NULL)
{
loc=ptr;
ptr=ptr->next;
}
loc->next=(NODE *)NULL;
free(ptr);
}
}
void main()
{
int choice,item,after;
char ch;
clrscr();
start=NULL;
do
{ printf("ttttLINKED LISTn");
printf("1.Insert element at begining n");
printf("2.Insert element at end n");
printf("3.Traverse the linked listn");
printf("4.Delete from the beginingn");
printf("5.Delete from the lastn");
printf("6.Exitn");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the item:");
scanf("%d",&item);
insertatbegin(item);
break;
case 2: printf("Enter the item:");
scanf("%d",&item);
insert_at_end(item);
break;
case 3: printf("nTraversing the linked list:n");
traversinorder(start);
break;
case 4: printf("Deleted the itemn");
dele_beg();
40. break;
case 5: printf("Deleted the itemn");
dele_end(start);
break;
case 6: return;
}
fflush(stdin);
printf("Do your want to continue(y/n)?n");
scanf("%c",&ch);
}while((ch=='y')||(ch=='y'));
}
SAMPLE OUTPUT:
LINKED LIST
1.Insert element at begining
2.Insert element at end
3.Traverse the linked list
4.Delete from the begining
5.Delete from the last
6.Exit
Enter your choice:1
Enter the item:34
Do your want to continue(y/n)?
y
LINKED LIST
1.Insert element at begining
2.Insert element at end
3.Traverse the linked list
4.Delete from the begining
5.Delete from the last
6.Exit
Enter your choice:2
Enter the item:56
Do your want to continue(y/n)?
y
41. LINKED LIST
1.Insert element at begining
2.Insert element at end
3.Traverse the linked list
4.Delete from the begining
5.Delete from the last
6.Exit
Enter your choice:3
Traversing the linked list:
34
56
Do your want to continue(y/n)?
y
LINKED LIST
1.Insert element at begining
2.Insert element at end
3.Traverse the linked list
4.Delete from the begining
5.Delete from the last
6.Exit
Enter your choice:4
Deleted the item
Do your want to continue(y/n)?
n
42. EXPERIMENT NO.15
AIM:
Program to implement the solution to Josephus Problem using doubly circular linked list
INTRODUCTION:
The Josephus problem is about n number of soldiers who are in a circular queue. Starting
from the first soldier, soldiers are going to be eliminated on the basis of kill count which will
be entered by the user. After the elimination only one soldier would survive.
Example:
start
survivor
If n=7 and kill count=3, then soldiers will be eliminated in the following sequence:
3 6 2 7 5 1 and soldier 4 will be the survivor
SOURCE CODE :
#include<iostream.h>
#include<conio.h>
struct node
{
node *prev;
int value;
node *next;
};
void main()
{
clrscr();
int n;
cout<<"n Enter the number of soldiers: ";
cin>>n;
node *curnode=new node;
curnode->value=1;
node *temp=curnode;
for(int i=2;i<=n;i++) //Creating circular doubly linked list
{
curnode->next=new node;
curnode->next->prev=curnode;
curnode=curnode->next;
curnode->value=i;
}
curnode->next=temp;
curnode->next->prev=curnode;
curnode=curnode->next;
43. int k;
cout<<"n Enter kill count: ";
cin>>;
int c=1;
while(curnode->next!=curnode)
{
if(c==k)
{
cout<<"n Killed: "<<curnode->value;
curnode->prev->next=curnode->next;
curnode->next->prev=curnode->prev;
node *next=curnode->prev->next;
delete(curnode);
curnode=next;
c=1;
}
else
{
curnode=curnode->next;
c++;
}
}
cout<<"n Survivor: "<<curnode->value;
delete(curnode);
getch();
}
SAMPLE OUTPUT:
Enter the number of soldiers:11
Enter kill count:3
Killed:3
Killed:6
Killed:9
Killed:1
Killed:5
Killed:10
Killed:4
Killed:11
Killed:8
Killed:2
Survivor:7
EXPERIMENT NO.16
44. AIM:
Program to traverse a binary tree in pre-order, in-order and post-order
INTRODUCTION:
Inorder traversal (Symmetric order)
Traverse (inorder) the left sub tree
Visit the root node
Traverse (inorder) the right sub tree
Preorder traversal
Visit the root node
Traverse(preorder) the left sub tree
Traverse (preorder) the right sub tree
Postorder traversal
Traverse(postorder) the left sub tree
Traverse (postorder) the right sub tree
Visit the root node
Example:
Inorder: GDBEACF
Preorder: ABDGECF
Postorder: GDEBFCA
SOURCE CODE :
#include<iostream.h>
#include<stdio.h>
#include<process.h>
#include<conio.h>
#include<alloc.h>
struct rec
{
long num;
struct rec *left;
struct rec *right;
45. };
struct rec *tree=NULL;
struct rec *insert(struct rec *tree,long num);
int select();
void preorder(struct rec *tree);
void inorder(struct rec *tree);
void postorder(struct rec *tree);
int count=1;
void main()
{
clrscr();
int choice;
long digit;
do
{
choice=select();
switch(choice)
{
case 1: puts("Enter integer: To quit enter 0");
cin>>digit;
while(digit!=0)
{
tree=insert(tree,digit);
cin>>digit;
}continue;
case 2: puts("npreorder traversing TREE");
preorder(tree);continue;
case 3: puts("ninorder traversing TREEE");
inorder(tree);continue;
case 4: puts("npostorder traversing TREE");
postorder(tree);continue;
case 5: puts("END");
exit(0);
}
}while(choice!=5);
}
int select()
{
int selection;
do
{
puts("nEnter 1: Insert a node in the BT");
puts("Enter 2: Display(preorder)the BT");
puts("Enter 3: Display(inorder)the BT");
puts("Enter 4: Display(postorder)the BT");
puts("Enter 5: END");
puts("Enter your choice");
cin>>selection;
if((selection<1)||(selection>5))
{
puts("wrong choice:Try again");
getch(); }
}while((selection<1)||(selection>5));
return (selection);
}
struct rec *insert(struct rec *tree,long digit)
{
if(tree==NULL)
{
tree=(struct rec *)malloc(sizeof(struct rec));
tree->left=tree->right=NULL;
46. tree->num=digit;count++;
}
else
if(count%2==0)
tree->left=insert(tree->left,digit);
else
tree->right=insert(tree->right,digit);
return(tree);
}
void preorder(struct rec *tree)
{
if(tree!=NULL)
{
cout<<"n"<<tree->num;
preorder(tree->left);
preorder(tree->right);
}
}
void inorder(struct rec *tree)
{
if(tree!=NULL)
{
inorder(tree->left);
cout<<"n"<<tree->num;
inorder(tree->right);
}
}
void postorder(struct rec *tree)
{
if(tree!=NULL)
{
postorder(tree->left);
postorder(tree->right);
cout<<"n"<<tree->num;
}
}
SAMPLE OUTPUT:
Enter 1: Insert a node in the BT
Enter 2: Display(preorder)the BT
Enter 3: Display(inorder)the BT
Enter 4: Display(postorder)the BT
Enter 5: END
Enter your choice
1
Enter integer: To quit enter 0
23
47. 45
67
0
Enter 1: Insert a node in the BT
Enter 2: Display(preorder)the BT
Enter 3: Display(inorder)the BT
Enter 4: Display(postorder)the BT
Enter 5: END
Enter your choice
2
preorder traversing TREE
23
45
67
Enter 1: Insert a node in the BT
Enter 2: Display(preorder)the BT
Enter 3: Display(inorder)the BT
Enter 4: Display(postorder)the BT
Enter 5: END
Enter your choice
3
inorder traversing TREEE
45
23
67
Enter 1: Insert a node in the BT
Enter 2: Display(preorder)the BT
Enter 3: Display(inorder)the BT
48. Enter 4: Display(postorder)the BT
Enter 5: END
Enter your choice
5
END
EXPERIMENT NO.17
AIM:
Program to implement binary search
INTRODUCTION:
To search a particular item with a certain target the approximate middle entry of the list is located and
its key value is examined. If its value is higher than the target, the key value of the middle entry of the
first half of the list is examined and the procedure is repeated on the first half until the required item is
found. If the value is lower than the target, the key value of the middle entry of the second half of the
list is examined and the procedure is repeated on the second half until the required item is found. This
procedure continues until the required key is found or the search intervals become empty.
Algorithm:
Search for target in a[low] to a[high]
mid =(low+high)/2
if target=a[mid]
return(mid)
if target<a[mid]
Search for target in a[low] to a[mid-1]
else
Search for target in a[mid+1] to a[high]
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,loc,mid,beg,end,n,flag=0,item;
clrscr();
printf("Enter number of elements:");
scanf("%d",&n);
printf("Enter the elements of the array:n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
49. }
printf("Enter the element to be searched:n");
scanf("%d",&item);
loc=0;
beg=0;
end=n-1;
while((beg<=end)&&(item!=a[mid]))
{
mid=((beg+end)/2);
if(item==a[mid])
{
printf("Search is successfuln");
loc=mid;
printf("Position of the item=%dn",loc+1);
flag=flag+1;
}
if(item<a[mid])
end=mid-1;
else
beg=mid+1;
}
if(flag==0)
printf("search is not successfulln");
getch();
}
SAMPLE OUTPUT:
Enter number of elements:5
Enter the elements of the array:
12
34
45
56
78
Enter the element to be searched:
56
Search is successful
Position of the item=4
EXPERIMENT NO.18
AIM:
Program to implement binary search tree
50. INTRODUCTION:
A binary search tree is a binary tree which is either empty or satisfies the following rules:
Value of the left node is less than the value of the root
Value of the right node is more than or equal to the value of the root
All the sub trees of left and right nodes observe the above rules
SOURCE CODE:
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct rec
{
long num;
struct rec *left;
struct rec *right;
};
struct rec *tree=NULL;
struct rec *delnum(long digit,struct rec *r);
struct rec *insert(struct rec *tree,long num);
void deletenode(long digit,struct rec *tree);
int select();
void search(struct rec *tree,long num);
void preorder(struct rec *tree);
void inorder(struct rec *tree);
void postorder(struct rec *tree);
void main()
{
int choice;
long digit;
clrscr();
int element;
do
{
choice=select();
switch(choice)
{
case 1: puts("Enter integer: To quit enter 0");
cin>>digit;
while(digit!=0)
{
tree=insert(tree,digit);
cin>>digit;
}continue;
case 2: puts("Enter the number to be search");
cin>>digit;
search(tree,digit);
continue;
case 3: puts("npreorder traversing TREE");
preorder(tree);continue;
case 4: puts("ninorder traversing TREEE");
inorder(tree);continue;
case 5: puts("npostorder traversing TREE");
51. postorder(tree);continue;
case 6: puts("Enter element which do you wanbt delete from
the BST");
cin>>digit;
deletenode(digit,tree);continue;
case 7: puts("END");exit(0);
}
}while(choice!=7);
}
int select()
{
int selection;
do
{
puts("Enter 1: Insert a node in the BST");
puts("Enter 2: Search a node in BST");
puts("Enter 3: Display(preorder)the BST");
puts("Enter 4: Display(inorder)the BST");
puts("Enter 5: Display(postorder) the BST");
puts("Enter 6: Delete the element");
puts("Enter 7: END");
puts("Enter your choice");
cin>>selection;
if((selection<1)||(selection>7))
{
puts("wrong choice:Try again");
getch(); }
}while((selection<1)||(selection>7));
return (selection);
}
struct rec *insert(struct rec *tree,long digit)
{
if(tree==NULL)
{
tree=(struct rec *)malloc(sizeof(struct rec));
tree->left=tree->right=NULL;
tree->num=digit;
}
else
if(digit<tree->num)
tree->left=insert(tree->left,digit);
else
if(digit>tree->num)
tree->right=insert(tree->right,digit);
else if(digit==tree->num)
{
puts("Duplicate node:program exited");exit(0);
}
return(tree);
}
struct rec *delnum(long digit,struct rec *r)
{
struct rec *q;
if(r->right!=NULL)delnum(digit,r->right);
else
q->num=r->num;
q=r;
r=r->left;
return(q);
}
53. }
SAMPLE OUTPUT:
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice
1
Enter integer: To quit enter 0
2
3
4
5
6
0
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice
4
inorder traversing TREEE
2
54. 3
4
5
6
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice
2
Enter the number to be search
67
The number does not exits
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice
7
END
55. EXPERIMENT NO.19
AIM:
Program to implement sorting of data using:
a) Bubble sort
b) Selection sort
c) Insertion sort
d) Quick sort
e) Merge sort
f) Heap sort
INTRODUCTION:
Bubble Sort
Multiple swapping take place in one pass. Smaller elements move or bubble up to the top of the list.
Adjacent members of the list to be sorted are compared. For obtaining ascending order, if the item on
left is greater than the item immediately right to it, they are swapped. This process is carried on till the
list is sorted.
Example:
List: 85 66 53 33 27
Pass I 66 53 33 27 85
Pass II 53 33 27 66 85
Pass III 33 27 53 66 85
Pass IV 27 33 53 66 85
SelectionSort
Perform a search through the table starting from the first record to locate the element with the smallest
key. Interchange it with the first record. Thus, the smallest key is placed in the first position. In the
second iteration, locate the second smallest key, examining the keys of the records starting from the
second record onwards. Interchange it with the second record. Continue the process until all records
are sorted.
Example:
List: 45 25 75 15 65 55 95 35
Pass I 15 25 75 45 65 55 95 35
Pass II 15 25 75 45 65 55 95 35
Pass III 15 25 35 45 65 55 95 75
56. Pass IV 15 25 35 45 65 55 95 75
Pass V 15 25 35 45 55 65 95 75
Pass VI 15 25 35 45 55 65 95 75
Pass VII 15 25 35 45 55 65 75 95
Insertion Sort:
Suppose an array A with n elements A[1], A[2]…..A[n] is in memory. The insertion sort algorithm
scans A from A[1] to A[n], inserting each element A[k] into its proper position in the previously
sorted sub array A[1],A[2]…. A[k-1].
Example:
List: 77 33 44 11 88 22 55
Pass I 77 33 44 11 88 22 55
Pass II 33 77 44 11 88 22 55
Pass III 33 44 77 11 88 22 55
Pass IV 11 33 44 77 88 22 55
Pass V 11 33 44 77 88 22 55
Pass VI 11 22 33 44 77 88 55
Pass V 11 22 33 44 55 77 88
Quick Sort:
Choose some key from the list. Call this key the pivot. Then partition the items so that all those with
keys less than pivot come in one sub list and all those with greater key come in another. Sort the two
reduced list separately and continue the process till the list gets sorted.
Example:
List: 24 56 47 35 10 90 82 31
Pass I 10 24 56 47 35 90 82 31
Pass II 10 24 47 35 31 56 82 90
Pass III 10 24 35 31 47 56 82 90
Pass IV 10 24 31 35 47 56 82 90
Pass V 10 24 31 35 47 56 82 90
Merge Sort:
57. Given a sequence of n elements, A[1],A[2],………………………..A[n], spit it into two sets
A[1],A[2],………..A[n/2] and A[(n/2)+1]…………….A[n]. Successively select the data
element with the smallest key occurring in either of the sets and place this element in a new
array.
Example:
List: 11 20 35 42 9 22 50
X 11 20 35 42
Y 9 22 50
Z 9 11 20 22 35 42 50
Heap Sort:
Heap sorting comprises of two steps:
Creation of heap
Processing of heap
A heap is defined to be a binary tree with a key in each node such that:
All leaves of the tree are on two adjacent levels
All leaves on the lowest level occur to the left and all levels, except possibly the lowest are
filled.
The key in the root is at least as large as the keys of its children (if any) and the left and the
right sub trees (if they exist) are again heaps.
Example:
List: 8 20 9 4 15 10 7 22 3 12
Creation of heap:
……………………
Processing of heap:
Replace root with the last unprocessed node i.e. 22 will be replaced by 8
The resultant binary tree,except 22, should be made into a heap
Continue the process until all nodes are processed.
58. SOURCE CODE:
Experiment 19 (a): Program to implement Bubble Sort
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,temp;
clrscr();
printf("How many elements:");
scanf("%d",&n);
printf("Enter the element of array:n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Elements of array after bubble sorting are:n");
for(i=0;i<=n-1;i++)
{
printf("%dn",a[i]);
}
getch();
}
SAMPLE OUTPUT:
How many elements:5
Enter the element of array:
12
34
23
56
45
Elements of array after bubble sorting are:
59. 12
23
34
45
56
Experiment 19 (b): Program to implement Selection Sort
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,temp,loc,min;
clrscr();
printf("nEnter number of elements:n");
scanf("%d",&n);
printf("Enter the elements of array:n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
min=a[0];
for(i=0;i<=n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<=n-1;j++)
{
if(a[j]<min)
{
min=a[j];
loc=j;
}
}
if(loc!=1)
{
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
}
printf("The array after selection sort is:n");
for(i=0;i<=n-1;i++)
{
printf("%dn",a[i]);
}
getch();
}
SAMPLE OUTPUT:
Enter number of elements:
60. 7
Enter the elements of array:
12
34
2
3
6
7
8
The array after selection sort is:
2
3
6
7
8
12
34
Experiment 19 (c): Program to implement Insertion Sort
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,k,i,j,temp;
clrscr();
printf("How many elements:n");
scanf("%d",&n);
printf("Enter the elements of array:");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
for(k=1;k<=n-1;k++)
{
temp=a[k];
j=k-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
61. }
printf("Elements of array after insertion sort:n");
for(i=0;i<=n-1;i++)
{
printf("%dn",a[i]);
}
getch();
}
SAMPLE OUTPUT:
How many elements:
5
Enter the elements of array:78
45
34
12
67
Elements of array after insertion sort:
12
34
45
67
78
Experiment 19 (d): Program to implement Quick Sort
#include<stdio.h>
#include<conio.h>
#define max 100
int a[max],n,i,l,h;
void main()
{
clrscr();
void input(void);
input();
getch();
}
void input(void)
{
void output(int a[],int n);
void quick_sort(int a[],int l,int h);
printf("How many elements in the array : ");
scanf("%d",&n);
printf("n");
62. printf("Enter the elements : n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
l=0;
h=n-1;
quick_sort(a,l,h);
printf("Sorted Array :n");
output(a,n);
}
void quick_sort(int a[],int l, int h)
{
int temp,key,low,high;
low=l;
high=h;
key=a[(low+high)/2];
do
{
while(key>a[low])
{
low++;
}
while(key<a[high])
{
high--;
}
if(low<=high)
{
temp=a[low];
a[low++]=a[high];
a[high--]=temp;
}
} while(low<=high);
if(l<high)
quick_sort(a,l,high);
if(low<h)
quick_sort(a,low,h);
}
void output(int a[],int n)
{
for(i=0;i<=n-1;i++)
{
printf("%dn",a[i]);
}
}
SAMPLE OUTPUT:
How many elements in the array : 5
Enter the elements :
56
34
23
63. 78
45
Sorted Array :
23
34
45
56
78
Experiment 19 (e): Program to implement Merge Sort
#include<stdio.h>
#include<conio.h>
#define MAX 10
void merge(int *arr, int *temp, int low, int mid, int high);//function
prototype for merge sorting
/*function for merge sorting*/
void m_sort(int *arr, int *temp, int low, int high)
{
int mid;
if(high>low)
{
mid = (low+high)/2;//middle element
m_sort(arr,temp,low,mid);
m_sort(arr,temp,mid+1,high);
merge(arr,temp,low,mid+1,high);
}
}
void merge(int *arr, int *temp, int low, int mid, int high)
{
int i,end,num,pos;
end = mid-1;
pos = low;
num = high-low+1;
while((low<=end) && (mid<=high))
{
if(arr[low]<=arr[mid])
{
temp[pos] = arr[low];
pos = pos + 1;
low = low + 1;
}
else
{
temp[pos] = arr[mid];
pos = pos + 1;
mid = mid + 1;
64. }
}
while(low<=end)
{
temp[pos] = arr[low];
low = low + 1;
pos = pos + 1;
}
while(mid<=high)
{
temp[pos] = arr[mid];
mid = mid + 1;
pos = pos + 1;
}
for(i=0;i<num;i++)
{
arr[high] = temp[high];
high = high - 1;
}
}
void main()
{
int num,arr[MAX],temp[MAX],i;
clrscr();
printf("nEnter the number of elements :");
scanf("%d",&num);
if(num>MAX)
printf("nArray out of bound!");
else
{ printf("nEnter elements:");
for(i=0;i<num;i++)
scanf("%d",&arr[i]);
m_sort(arr,temp,0,num);
printf("nThe list after sorting is :n");
for(i=0;i<num;i++)
printf("n%d",arr[i]);
}
getch();
}
SAMPLE OUTPUT:
Enter the number of elements :5
Enter elements:12
34
55
34
2
The list after sorting is :
65. 2
12
34
34
55
Experiment 19 (f): Program to implement heap sort
SOURCE CODE :
#include <stdio.h>
#include <conio.h>
void makeheap ( int [ ], int ) ;
void heapsort ( int [ ], int ) ;
void main( )
{
int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
clrscr( ) ;
printf ( "Heap Sortn" ) ;
makeheap ( arr, 10 ) ;
printf ( "nBefore Sorting:n" ) ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%dt", arr[i] ) ;
heapsort ( arr, 10 ) ;
printf ( "nAfter Sorting:n" ) ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%dt", arr[i] ) ;
getch( );
}
void makeheap ( int x[ ], int n )
{
int i, val, s, f ;
for ( i = 1 ; i < n ; i++ )
{
val = x[i] ;
s = i ;
f = ( s - 1 ) / 2 ;
while ( s > 0 && x[f] < val )
{
x[s] = x[f] ;
s = f ;
f = ( s - 1 ) / 2 ;
}
66. x[s] = val ;
}
}
void heapsort ( int x[ ], int n )
{
int i, s, f, ivalue ;
for ( i = n - 1 ; i > 0 ; i-- )
{
ivalue = x[i] ;
x[i] = x[0] ;
f = 0 ;
if ( i == 1 )
s = -1 ;
else
s = 1 ;
if ( i > 2 && x[2] > x[1] )
s = 2 ;
while ( s >= 0 && ivalue < x[s] )
{
x[f] = x[s] ;
f = s ;
s = 2 * f + 1 ;
if ( s + 1 <= i - 1 && x[s] < x[s + 1] )
s++ ;
if ( s > i - 1 )
s = -1 ;
}
x[f] = ivalue ;
}
}
SAMPLE OUTPUT:
Heap Sort
Before Sorting:
90 57 25 13 11 9 17 1 2 3
After Sorting:
1 2 3 9 11 13 17 25 57 90
EXPERIMENT NO.20
AIM:
Program to implement a graph and traverse it using Breadth First Search
INTRODUCTION:
A graph is a structure G={V,E} in which V is a finite set of nodes and E is a finite set of
edges. It is represented by an adjacency matrix. An adjacency matrix for a graph with n
67. nodes is an nxn matrix. Any element of the adjacency matrix is either 0 or 1. Aij =1 if there is
an edge from Vi to Vj and Aij=0 if there is no such edge.
Breadth First Search:
Step 1: Start with any vertex and mark it as visited.
Step 2: Using the adjacency matrix of the graph, find a vertex adjacent to the vertex in step 1.
Mark it as visited.
Step 3: Return to vertex in step 1 and move along an edge towards an unvisited vertex, and
mark the new vertex as visited.
Step 4: Repeat step 3 until all vertices adjacent to the vertex, as selected in step 2, have been
marked as visited.
Step 5: Repeat step 1 through step 4 starting from the vertex visited in step 2, then starting
from the nodes visited in step 3 in the order visited. If all vertices have been visited, then
continue to next step.
Step 6: Stop
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void insert(int);
int q[20],r=-1,g[7][7],row;
void insert(int x)
{
r++;
q[r]=x;
}
remove()
{
int item,k;
item=q[0];
for(k=0;k<r;k++)
q[k]=q[k+1];
r--;
return(item);
}
void main()
{
int i,j, num,w,visited[10],v,j1;
int l,vertices[10],count=0,final[10];
clrscr();
randomize();
printf("Enter no. of vertices:");
scanf("%d", &row);
printf("nAdjacency Matrix:nn");
printf(" ");
for(j=0;j<row;j++)
printf(" Vertex %d ",j);
for(i=0;i<row;i++)
{
for(j=count;j<row;j++)
{