Data Sturcture and Algorithm Lab Manual
Data Sturcture and Algorithm Lab Manual
LIST OF EXERCISES
1
INDEX
1a Stack-Array Implementation
1b Queue-Array Implementation
2 List-Array Implementation
4a Polynomial Addition
5 Binary Tree
7a Bubble sort
7b Selection sort
7c Insertion sort
2
Ex.No.-1a STACK – ARRAY IMPLEMENTATION
AIM:
To write a C program to implement the stack using arrays.
ALGORITHM:
(i) Push Operation:
o To push an element into the stack, check whether the top of the stack is
greater than or equal to the maximum size of the stack.
o If so, then return stack is full and element cannot be pushed into the stack.
o Else, increment the top by one and push the new element in the new position
of top.
(ii) Pop Operation:
o To pop an element from the stack, check whether the top of the stack is
equal to -1.
o If so, then return stack is empty and element cannot be popped from
the stack. o Else, decrement the top by one.
PROGRAM:
# include <stdio.h>
# include <conio.h>
# include
<stdlib.h> # define
size 5 struct stack
{
int s[size];
int top;
}st;
int stfull()
{
if(st.top>=size-1)
return 1;
else return 0;
}
3
{
if(st.top==-1)
return 1;
else return 0;
}
int pop()
{
int item;
item=st.s[st.top];
st.top--;
return(item);
}
void display()
{
int i;
if(stempty())
printf("Stack Is Empty!\n");
else
{
for(i=st.top;i>=0;i--)
printf("\n%d",st.s[i]);
}
}
void main(void)
{
int item,ch;
char ans;
st.top = -1;
clrscr();
printf("<-----Stack using Array- - - ->\n");
while(1)
{
printf("\n1.Push\n2.Pop\n3.Display\n4.exit\n");
printf("Enter Your Choice:\n");
scanf("%d",&ch); switch(ch)
{
case 1:
printf("Enter The item to be pushed:\n");
scanf("%d",&item);
if(stfull())
printf("Stack is Full!\n");
else
push(item);
break;
4
case 2:
if(stempty())
printf("Empty stack!\n");
else
{
item=pop();
printf("The popped element is %d\n",item);
}
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
getch();
}
OUTPUT:
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice:
1
Enter The item to be pushed: 10
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice:
1
Enter The item to be pushed: 20
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice: 3
20
5
10
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice: 2
The popped element is
20
1. Push
2.Pop
3.Display
4.exit
Enter Your Choice: 4
RESULT:
Thus a C program to implement the stack using arrays is written and executed
successfully.
6
Ex.No.-1b QUEUE – ARRAY IMPLEMENTATION
AIM:
To write a C program to implement the queue using arrays.
ALGORITHM:
Enqueue:
Dequeue:
PROGRAM:
void insert_element( );
void delete_element(
); void display_queue(
);
int main( )
{
int option;
printf(">>> c program to implement queue operations
<<<"); do
{
printf("\n\n 1.Enqueue an element");
printf("\n 2.Dequeue an element");
printf("\n 3.Display queue");
7
printf("\n 4.Exit");
8
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
insert_element();
break;
case 2:
delete_element();
break;
case 3:
display_queue();
break;
case 4:
return 0;
}
}while(option!=4);
}
void insert_element( )
{
int num;
printf("\n Enter the number to be Enqueued: ");
scanf("%d",&num);
if(front==0 && rear==MAX-1)
printf("\n Queue OverFlow Occured");
else if(front==-1&&rear==-1)
{
front=rear=0;
queue[rear]=num;
}
else if(rear==MAX-1 && front!=0)
{
rear=0;
queue[rear]=num;
}
else
{
rear++;
queue[rear]=num;
}
}
void delete_element( )
{
int element;
if(front==-1)
9
{
printf("\n Underflow");
}
element=queue[front];
if(front==rear)
front=rear=-1;
else
{
if(front==MAX-1)
front=0;
else front++;
printf("\n The dequeued element is: %d",element);
}
void display_queue( )
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
OUTPUT:
1.Enqueue an element
2.Dequeue an element
10
3.Display queue
4.Exit
Enter your choice: 1
1.Enqueue an element
2.Dequeue an element
3.Display queue
4.Exit
Enter your choice: 2
1. Enqueue an element
2.Dequeue an
element 3.Display
queue 4.Exit
Enter your choice: 4
RESULT:
Thus a C program to implement the queue using arrays is written and executed
successfully.
11
Ex.No.-2 LIST – ARRAY IMPLEMENTATION
AIM:
To write a C program to implement the List using arrays.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 10
void create( );
void insert( );
void deletion( );
void search( );
void display ();
int a,b[20], n, p, e, f, i, pos;
void main( )
{
int ch;
char g='y';
do
{
12
printf("\n Main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice:");
scanf("%d", &ch);
switch(ch)
{
case 1:
create();
break;
case 2:
deletion();
break;
case 3:
search();
break;
case 4:
insert();
break;
case 5:
display();
break;
case 6:
exit();
break;
default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}
void create( )
{
printf("\n Enter the number of nodes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}
}
13
void deletion( )
{
printf("\n Enter the position u want to
delete:"); scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location:");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion:");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}
void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);
for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list:", e);
continue;
}
}
}
void insert()
{
14
printf("\n Enter the position u need to insert:");
scanf("%d", &pos);
if(pos>=n)
{
printf("\n invalid Location:");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert:");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion:");
display();
}
void display()
{
printf("\n The Elements of The list ADT
are:"); for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}
OUTPUT:
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:1
Do u want to continue:y
Main Menu
1.Create
2.De ete
3.Search
4.Ins rt
5.Display
6.Exi
Enter your Choice:2
Enter the position u want to delete:2
Elements after deletion: 11 33 44
Do u want to continue:y
Main Menu
1.Create
2.De ete
3.Search
4.Ins rt
5.Display
6.Exi
Enter your Choice:3
Do u want to continue:y
Main Menu
1.Create
2.De ete
3.Search
4.Insert
5.Display
6.Exi
Enter your Choice:4
Enter the position u need to insert:2
Enter the element to insert:25
The l st after insertion: 11 25 33 44
16
Do u want to continue:y
Main Menu
1. Create
2. Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:5
Do u want to continue:y
Main Menu
1. Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:6
RESULT:
Thus a C program to implement the List using array is written and executed
successfully.
17
Ex.No.-3a LIST – LINKED LIST IMPLEMENTATION
AIM:
To write a C program to implement the List ADT using linked list.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/*declaring a structure to create a node*/
struct node
{
int data;
struct node *next;
};
struct node *start;
/* inserting nodes into the list*/
/*function to insert values from beginning of the the single
linked list*/ void insertbeg(void)
{
struct node *nn;
int a;
/*allocating implicit memory to the node*/
nn=(struct node *)malloc(sizeof(struct node));
18
printf("enter data:");
scanf("%d",&nn->data);
a=nn->data;
if(start==NULL)
/*checking if List is empty*/
{
nn->next=NULL;
start=nn;
}
else
{
nn->next=start;
start=nn;
}
printf("%d succ. inserted\n",a);
return;
}
/*function to insert values from the end of the linked list*/
void insertend(void)
{
struct node *nn,*lp;
int b;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
b=nn->data;
if(start==NULL)
{
nn->next=NULL;
start=nn;
}
else
{
lp=start;
while(lp->next!=NULL)
{
lp=lp->next;
}
lp->next=nn;
nn->next=NULL;
}
printf("%d is succ. inserted\n",b);
return;
}
/*function to insert values from the middle of the linked list*/
void insertmid(void)
{
19
struct node *nn,*temp,*ptemp;
int x,v;
nn=(struct node *)malloc(sizeof(struct node));
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("enter data before which no. is to be inserted:\n");
scanf("%d",&x);
if(x==start->data)
{
insertbeg();
return;
}
ptemp=start;
temp=start->next;
while(temp!=NULL&&temp->data!=x)
{
ptemp=temp;
temp=temp->next;
}
if(temp==NULL)
{
printf("%d data does not exist\n",x);
}
else
{
printf("enter data:");
scanf("%d",&nn->data);
v=nn->data;
ptemp->next=nn;
nn->next=temp;
printf("%d succ. inserted\n",v);
}
return;
}
void deletion(void)
{
struct node *pt,*t;
int x;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("enter data to be deleted:");
20
scanf("%d",&x);
if(x==start->data)
{
t=start;
/* assigning first node pointer to next node pointer to delete a
data from the starting of the node*/
start=start->next;
free(t);
printf("%d is succ. deleted\n",x);
return;
}
pt=start;
t=start->next;
while(t!=NULL&&t->data!=x)
{
pt=t;t=t->next;
}
if(t==NULL)
{
printf("%d does not exist\n",x);
return;
}
else
{
pt->next=t->next;
}
printf("%d is succ. deleted\n",x);
free(t);
return;
}
void display(void)
{
struct node *temp;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("elements are:\n");
temp=start; while(temp!
=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
return;
}
21
/* main program*/
int main( )
{
int c,a;
start=NULL;
do
{
printf("1:insert\n2:delete\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:
printf("1:insertbeg\n2:insert end\n3:insert mid\nenter choice:");
scanf("%d",&a);
switch(a)
{
case 1:insertbeg(); break;
case 2:insertend(); break;
case 3:insertmid(); break;
} break;
case 2:deletion(); break;
case 3:display(); break;
case 4:printf("program ends\n");break;
default:printf("wrong choice\n"); break;
}
}while(c!=4);
return 0;
}
22
OUTPUT:
RESULT:
Thus a C program to implement the List ADT using linked list is written and
executed successfully.
23
Ex.No.-3b STACK – LINKED LIST IMPLEMENTATION
AIM:
To write a C program to implement the stack using linked list.
ALGORITHM:
A) Push Operation:
1. To push an element into the stack, copy the element to be inserted in the data field
of the new node.
2. Assign the reference field of the new node as NULL.
3. Check if top is not NULL, if so, then assign the value of top in the reference field
of new node.
4. Assign the address of the new node to the top.
B) Pop Operation:
1. To pop an element from the stack, check whether the top of the stack is NULL.
2. If so, then return stack is empty and element cannot be popped from the stack.
3. Else, assign the top value to a temporary node.
4. Now assign the value in the reference field of the node pointed by top to the top value.
5. Return the value in the data field of the temporary node as the element
deleted and delete the temporary node.
PROGRAM:
# include <stdio.h>
void push( );
void pop( );
void display( );
main( )
{
int n;
printf("STACK USING LINKED LIST\n1.PUSH\n 2.POP\n 3.DISPLAY\n 4.
EXIT \n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
push();
break;
24
case 2:
pop();
break;
case 3:
display( );
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}while(n!=4);
}
void push()
{
int item; n *temp;
printf("Enter the item\n");
scanf("%d",&item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=top;
top=temp;
}
void pop()
{
n *temp;
if(top==NULL)
printf("Stack is empty\n");
else
{
temp=top;
printf("The element deleted = %d\n",temp->data);
free(temp);
top=top->link;
}
}
void display()
25
{
n *save;
if(top==NULL)
printf("Stack is empty\n");
else
{
save=top;
printf("The elements of the stack are :");
while(save!=NULL)
{
printf("%d\t",save->data);
save=save->link;
}
printf("\nTopmost element = %d\n",top->data);
}
}
OUTPUT:
RESULT:
Thus a C program to implement the stack using linked list is written and executed
successfully.
26
Ex.No.-3c QUEUE – LINKED LIST IMPLEMENTATION
AIM:
To write a C program to implement the queue using linked list.
ALGORITHM:
Enqueue:
1. Create a new node and allocate memory space for the new node.
2. Assign the element to be inserted in the data field of the new node.
3. Assign NULL to the address field of the new node.
4. Check if rear and front pointers are NULL.
5. If so, then make the front and rear pointers to point to new node.
6. If not, then assign address of the new node as the rear
pointer value. Dequeue:
1. Check if queue is not empty.
2. If it is empty, return queue underflow and dequeue operation cannot be done.
3. If not, assign the front->next value as the new front pointer and free the deleted node.
PROGRAM:
void dequeue()
{
struct node *temp, *var=rear;
if(var==rear)
{
rear = rear->next;
free(var);
}
else
27
printf("\nQueue Empty");
}
void display()
{
struct node *var=rear;
if(var!=NULL)
{
printf("\nElements in Queue: ");
while(var!=NULL)
{
printf("\t%d",var->data);
var=var->next;
}
printf("\n");
}
else
printf("\nQueue is Empty");
}
int main( )
{
int ch;
clrscr();
front=NULL;
printf("<-----Queue using Linked List----->\n");
printf(" \n1. Enqueue an element");
printf(" \n2. Dequeue an element");
28
printf(" \n3. Display Queue");
printf(" \n4. Exit\n");
while(1)
{
printf(" \nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int value;
printf("\nEnter a value to Enqueue: ");
scanf("%d",&value);
enqueue(value);
display( );
break;
}
case 2:
{
dequeue( );
display( );
break;
}
case 3:
{
display( );
break;
}
case 4:
{
exit(0);
}
default:
{
printf("\nwrong choice for operation");
}
}
}
}
OUTPUT:
1. Enqueue an element
2. Dequeue an element
3. Display Queue
29
4. Exit
Enter your choice: 1
Elements in Queue: 10
Elements in Queue: 10 20
Elements in Queue: 10 20 30
Elements in Queue: 20 30
RESULT:
Thus a C program to implement the queue using linked list is written and executed
successfully.
30
31
Ex.No.-4a POLYNOMIAL ADDITION
AIM:
To write a C program to perform polynomial addition using linked list.
ALGORITHM:
PROGRAM:
# include <stdio.h>
# include <malloc.h>
# include <conio.h>
struct link
{
int coeff,pow;
struct link *next;
}*poly1=NULL, *poly2=NULL,*poly=NULL;
void polyadd(struct link *poly1, struct link *poly2, struct link *poly)
{
while(poly1->next && poly2->next)
{
if(poly1->pow > poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow < poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff + poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct link *) malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
32
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link *) malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}
void main(
)
{ poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
clrscr();
printf(“\n Enter the First Polynomial:”);
create(poly1);
printf(“\n Enter the Second Polynomial:”);
create(poly2);
polyadd(poly1,poly2,poly);
printf(“\n\t First Polynomial:”);
display(poly1);
printf(“\n\t Second Polynomial:”);
display(poly2);
printf(“\n\t Addition of two Polynomials:”);
display(poly);
getch();
OUTPUT:
Enter the First Polynomial:
Enter Coeff:3
Enter Power:3
Continue(y/n):y
Enter Coeff:6
Enter Power:2
Continue(y/n):y
33
Enter Coeff:9
34
Enter Power:1
Continue(y/n):y
Enter Coeff:8
Enter Power:0
Continue(y/n):n
Enter Coeff:43
Enter Power:2
Continue(y/n):y
Enter Coeff:23
Enter Power:1
Continue(y/n):y
Enter Coeff:24
Enter Power:0
Continue(y/n):n
RESULT:
Thus a C program to perform polynomial addition using linked list is written and
executed successfully.
35
Ex.No.-4b INFIX TO POSTFIX CONVERSION
AIM:
To write a C program to perform infix to postfix conversion using stack.
ALGORITHM:
1. Define a stack
2. Go through each character in the string
3. If it is between 0 to 9, append it to output string.
4. If it is left brace push to stack
5. If it is operator *+-/ then
a. If the stack is empty push it to the stack
b. If the stack is not empty then start a loop:
i. If the top of the stack has higher precedence
ii. Then pop and append to output string
iii. Else break
iv. Push to the stack
6. If it is right brace then
a. While stack not empty and top not equal to left brace
b. Pop from stack and append to output string
c. Finally pop out the left brace.
7. If there is any input in the stack pop and append to the output string.
PROGRAM:
# define SIZE 50
# include <ctype.h>
char s[SIZE];
int top = -1;
push(char elem)
{
s[++top] = elem;
35
}
char pop()
{
return (s[top--]);
}
main(
)
{ char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("<-----Stack Application: Infix to Postfix Conversion-----
>\n"); printf("\n\nRead the Infix Expression ?
"); scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0')
{
if (ch == '(')
push(ch);
else if
(isalnum(ch))
pofx[k++] = ch;
else if (ch == ' )' )
{
while (s[top] != ' ( ' )
pofx[k++] = pop( );
elem = pop( );
}
else
{
36
while (pr(s[top]) >= pr(ch))
37
pofx[k++] = pop( );
push(ch);
}
}
while (s[top] != '#')
pofx[k++] = pop( );
pofx[k] = '\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
}
OUTPUT:
RESULT:
Thus a C program to convert the expression in infix to postfix is written and executed
successfully.
38
Ex.No.-4c EVALUATING POSTFIX EXPRESSION
AIM:
To write a C program to evaluate postfix expression using stack.
ALGORITHM:
1. Start the program.
2. Scan the Postfix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the stack. If the scanned character
is an operator, there will be atleast two operands in the stack.
5. If the scanned character is an Operator, then we store the top most element of the
stack(topStack) in a variable temp. Pop the stack. Now evaluate
topStack(Operator)temp. Pop the stack and Push result into the stack.
6. Repeat this step till all the characters are scanned.
7. After all characters are scanned, we will have only one element in the stack. Return
topStack.
8. Stop the program.
PROGRAM:
# define SIZE 50
# include <ctype.h>
int s[SIZE];
int top=-1;
push(int elem)
{
s[++top]=elem;
}
int pop( )
{
return(s[top--]);
}
main( )
{
39
char pofx[50],ch;
int i=0,op1,op2;
printf("<-----Stack Application: Evaluating Postfix Expression----->\n");
printf("\n\nRead the Postfix Expression ?
"); scanf("%s",pofx);
while( (ch=pofx[i++]) != '\0')
{
if(isdigit(ch))
push(ch-'0');
else
{
op2=pop( );
op1=pop( );
switch(ch)
{
case '+':
push(op1+op2);
break;
case '-':
push(op1-op2);
break;
case '*':
push(op1*op2);
break;
case '/':
push(op1/op2);
break;
}
}
}
printf("\n Given Postfix Expn: %s\n",pofx);
printf("\n Result after Evaluation: %d\n",s[top]);
}
OUTPUT:
RESULT:
Thus a C program to evaluate the postfix expression is written and executed
successfully.
40
Ex.No.-5 BINARY TREE
AIM:
To write a C program to implement binary tree and its traversals.
ALGORITHM:
1. Start the program.
2. Declare the node.
3. Create the binary tree by inserting elements into it.
4. Traverse the binary tree by inorder and display the nodes.
5. Traverse the binary tree by preorder and display the nodes.
6. Traverse the binary tree by postorder and display the nodes.
7. Stop the program.
PROGRAM:
# include <stdio.h>
# include <alloc.h>
# include
<conio.h>
void main( )
{
int choice;
char ans='n';
node *newnode,*root;
root=NULL;
clrscr ( ) ;
do
40
{
printf("\n\t Program for Binary Tree
Travesal"); printf("\n\t 1.Create");
printf("\n\t 2.Inorder");
printf("\n\t 3.Preorder");
printf("\n\t 4.Postorder");
printf("\n\t 5.Exit");
printf("\n\t Enter your Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
root=NULL;
do
{
newnode=getnode(); printf("\n\
tEnter the element:");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
printf("\n\tDo u want to enter more elements?(y/n):
"); ans=getche();
}while(ans=='y' || ans=='Y');
clrscr();
break;
case 2:
if(root==NULL)
printf("\n\t Tree is not created.");
else
inorder(root);
break;
case 3:
if(root==NULL)
printf("\n\t Tree is not created.");
else
preorder(root);
break;
case 4:
if(root==NULL)
printf("\n\t Tree is not created.");
else
postorder(root);
break;
41
}
}while(choice!=5);
}
node *getnode()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
if(root->left==NULL)
{
root->left=newnode;
}
else
insert(root->left,newnode);
}
}
43
}
}
}
OUTPUT:
45
Do u want to enter more elements?(y/n):n
RESULT:
Thus a C program to implement the tree and tree traversals is written and executed
successfully.
46
Ex.No.-6 GRAPH TRAVERSAL
AIM:
To write a C program to implement graph traversals by Breadth First Search and
Depth First Search.
ALGORITHM:
Breadth First Search:
1. Start the program.
2. Read the number of vertices and adjacency matrix.
3. Read the vertex from which to traverse the graph.
4. Initialize the visited array to 1 and insert the visited vertex in the queue.
5. Visit the vertex which is at the front of the queue.
6. Delete it from the queue and place its adjacent nodes in the queue.
7. Repeat the steps 5 & 6 , till the queue is not empty.
8. Display the traversal path.
9. Stop the program.
Depth First Search:
1. Start the program.
2. Read the number of vertices and adjacency matrix.
3. Initialize the visited array to 1.
4. Traverse the path one by one and push the visited vertex in the stack.
5. When there is no vertex further, we traverse back and search for unvisited vertex.
6. Display the traversal path.
7. Stop the program.
a) Breadth First
Search PROGRAM:
#include<stdio.h>
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;
void bfs(int v) {
62
for(i = 1; i <= n; i++)
if(a[v][i] && !
visited[i]) q[++r] = i;
if(f <= r) {
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main() {
int v;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
63
OUTPUT:
Enter the number of vertices : 4
form:
1 1 1 1
0 1 0 0
0 0 1 0
0 0 0 1
1 2 3 4
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
DFS(0);
}
64
void DFS(int i)
65
{
int j; printf("\n
%d",i);
visited[i]=1;
for(j=0;j<n;j++) if(!
visited[j]&&G[i][j]==1)
DFS(j);
}
OUTPUT:
Enter number of vertices : 8
Enter adjacency matrix of the graph :
0 1 1 1 1 0 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 0 1 0
1 0 0 0 0 0 1 0
0 1 1 0 0 0 0 1
0 0 0 1 1 0 0 1
0 0 0 0 0 1 1 0
0
1
5
2
7
6
3
4
RESULT:
Thus a C program to implement graph traversals by Breadth First Search and
Depth First Search is written and executed successfully.
66
Ex.No.-7 SORTING
AIM:
To write a C program to perform insertion sort, selection sort, and bubble sort.
ALGORITHM:
Insertion Sort
1. Get the n elements to be sorted.
2. The ith element is compared from (i-1)th to 0th element and placed in proper
position according to ascending value.
3. Repeat the above step until the last
element.
Selection sort:
4. Move the starting position of the unsorted portion of the array one step to the right.
5. Repeat steps 2 through 4 for the remainder of the unsorted portion of the array.
6. Continue this process until the entire array is sorted.
Bubble Sort
1. Get the n elements to be sorted.
2. Compare the first two elements of the array and swap if necessary.
3. Then, again second and third elements are compared and swapped if it is necessary
and continue this process until last and second last element is compared and swapped.
4. Repeat the above two steps n-1 times and print the result.
PROGRAM:
72
SELECTION SORT:
#include <stdio.h>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
73
INSERTION SORT:
#include <stdio.h>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
BUBBLE SORT:
#include <stdio.h>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
RESULT:
Thus a C program to perform insertion sort, selection sort, and bubble sort is written
and executed successfully.
75
Ex.No.-8 RECURSIVE BINARY SEARCH TREE
AIM:
To write a C program to implement Recursive Binary Search Tree.
ALGORITHM:
1. Start the program.
2. Declare the node.
3. Read the elements to be inserted.
4. Create the binary search tree.
5. Read the element to be searched.
6. Visit the nodes by inorder.
7. Find the searching node and display if it is present with parent node.
8. Read the element to be removed from BST.
9. Delete that node from BST.
10. Display the binary search tree by inorder.
11. Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a tree node
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
return root;
}
return 0;
}
78
RESULT:
Thus a C program to implement recursive binary search tree is written and executed
successfully.