DSA Lab Manual
DSA Lab Manual
(AUTONOMOUS)
LABORATORY RECORD
Name :
Register No. :
&
LABORATORY RECORD
Certified that this is the Bonafide Record of work done by the above student in the
Aim:
To sort an array of n numbers using Insertion Sort.
Algorithm:
1. Select the first element of the list (i.e., Element at first positionin the list).
2. Compare the selected element with all the other elements in thelist.
3. In every comparison, if any element is found smaller than theselected element (for
ascending order), then both are swapped.
4. Repeat the same procedure with element in the next position inthe list till the entire
list is sorted.
1
Program:
#include<stdio.h>
#include<conio.h>
void main(){
int size,i,j,temp,list[100];
clrscr();
printf("Enter the size of the List: ");
scanf("%d",&size);
printf("Enter %d integer values: ",size);
for(i=0; i<size;i++)
scanf("%d",&list[i]);
//Selection sort logic
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(list[i] > list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
2
printf("List after sorting is: ");
for(i=0; i<size; i++)
printf(" %d",list[i]);
getch();
}
Output:
Result:
3
Exp No: 1.b IMPLEMENTATION OF QUICK SORT
Date :
Aim:
Algorithm:
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Select an pivot element x from Ai
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai < x and Ai > x)
7. Stop
4
Program:
/* Quick Sort */
#include <stdio.h>
#include <conio.h>
void qsort(int arr[20], int fst, int last);
void main()
{
int arr[30];
int i,size;
clrscr();
printf("Enter total no. of the elements : ");
scanf("%d", &size);
printf("Enter total %d elements : \n", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
qsort(arr,0,size-1);
printf("\n Quick sorted elements \n");
for(i=0; i<size; i++)
printf("%d\t", arr[i]);getch();
}
void qsort(int arr[20], int fst, int last)
{
int i, j, pivot, tmp;
if(fst < last)
{
pivot = fst; i = fst; j = last;
while(i < j)
{
while(arr[i] <=arr[pivot] && i<last)
i++;
while(arr[j] > arr[pivot])
5
j--;
if(i <j )
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = tmp;
qsort(arr, fst, j-1);
qsort(arr, j+1,last);}
}
Output:
Enter total no. of the elements : 8
Enter total 8 elements :
1
-1
-2
3
Quick sorted elements
-2 -1 0 1 2 3 4 7
Result:
6
Exp No: 1.c IMPLEMENTATION OF INSERTION SORT
Date :
Aim:
Algorithm:
1. Start
• In pass p, move the element in position p left until its correct place is found among
the first p + 1 element.
• Element at position p is saved in temp, and all larger elements (prior to position
p) are moved one spot to the right. Then temp is placed in the correct spot.
5. Stop
7
Program:
/* Insertion Sort */
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, n, temp, a[20], p=0;
clrscr();
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i];
j = i - 1;
while ((temp<a[j]) && (j>=0))
{
a[j+1] =a[j];
j = j - 1;
a[j+1] = temp;
}p++;
printf("\n After Pass %d: ",p);for(k=0;
k<n; k++)
printf("%d", a[k]);
}printf("\n Sorted List: ");
for(i=0; i<n; i++) printf("
%d", a[i]);getch();
}
8
OUTPUT:
Result:
The insertion sort program was created and executed successfully.
9
Exp No: 2a IMPLEMENTATION OF SET OPERATIONS USING LINKED LIST
Date :
Aim:
To write a C Program to implement set operations using linked list.
Algorithm:
1. Start
2. Check if given data is present in a list using ispresent() function.
3. Function getUnion() get union of two linked lists head1 and head2
➢ Initialize the result list as NULL. Traverse list1 and add all of itselements
to the result.
➢ Traverse list2. If an element of list2 is already present in the resultthen do not
insert it to the result, otherwise insert.
➢ This method assumes that there are no duplicates in the givenlists
4. Function getInteraction() get intersection of two linked lists head1 andhead2
➢ Initialize the result list as NULL.
➢ Traverse list1 and look for every element in list2, if the element ispresent in
list2, then add the element to the result.
5. A function push() insert a node at the beginning of a linked list
6. Function printList() print a linkedlist.
7. Stop
10
Program:
// C program to find union
// and intersection of two unsorted
// linked lists
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
return result;
}
Output:
Result:
The implement set operation using linked list program was created and executedsuccessfully.
15
Ex No: 3.a IMPLEMENTATION OF STACK ADT USING ARRAY
Date :
Aim:
To write a C program to implement Stack ADT byusing arrays
Algorithm:
1. Create a Stack[ ] with MAX size as yourwish.
2. Write function for all the basic operations of stack - PUSH(),POP()and
DISPLAY().
3. By using Switch case, select push() operation to insert element inthestack.
• Step 1: Check whether stack is FULL. (top ==SIZE-1)
• Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is
notpossible!!!" and terminate the function.
• Step 3: If it is NOT FULL, then increment top value by one (top++)and set
stack[top]to value (stack[top] = value).
16
5. Similarly, By using Switch case, select display() operation to displayallelement
from the stack.
• Step 1: Check whether stack is EMPTY. (top ==-1)
• Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" andterminate
the function.
• Step 3: If it is NOT EMPTY, then define a variable 'i' and initializewith top.
Display stack[i] value and decrement i value by one (i--).
6. Step 3: Repeat above step until i value becomes'0'.Close theprogram.
17
Program:
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void); void
display(void);
int main()
{
//clrscr();top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");printf("\n\t
");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();break;
}
case 2:
{
pop();
break;
}
case 3:
18
{
display();break;
}
case 4:
{
printf("\n\t EXIT POINT ");break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
while(choice!=4);return
0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++; stack[top]=x;
}
void pop()
19
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}
20
Output:
Result:
Thus to implement Stack ADT by using array program was createdand executed
successfully.
21
Exp No: 3.b IMPLEMENTATION OF STACK USING LINKED LIST
Date :
Aim:
To write a c program to implement stack operations using linked list.
Algorithm:
1. Start
2. Define a singly linked list node forstack
3. Create Head node
4. Display a menu listing stackoperations
5. Accept choice
6. If choice = 1 then
• Create a new node with data Make new node point to first node
• Make head node point to new node
• Else If choice = 2 then
• Make temp node point to first node
• Make head node point to next of temp node Releasememory
• Else If choice = 3 then
• Display stack elements starting from head node till null
7. Stop
22
Program:
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch = 0; int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
23
scanf("%d", &temp->label);
h = head;
temp->next = h->next;
h->next = temp;
break;
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
/* Loop till last node */
while(h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;
case 4:
exit(0);
}
}
}
24
Output:
Result:
The implementation stack using linked list program was created and executed
successfully.
25
Exp No: 4.a IMPLEMENTATION OF STACK APPLICATION
Date : (Balancing Parenthesis)
Aim:
To write a c program for balancing parenthesis using stack.
Algorithm:
1. Start
2. Define an expression variable for the user to enter
3. Declare x and i
4. Initialize x= 0 and i = 0
5. Read the expression entered by the user
a. If it is open parenthesis, increment x by 1
b. If it is a close parenthesis, decrement x by 1
6. Increment i
7. If x is 0, expression has balanced parentheses
8. else it is unbalanced
9. Print the result
10. Stop
26
Program:
// C program to check the balanced parenthesis.
#include<stdio.h>
void main()
{
char expression[50]; // declaration of char type array
int x=0, i=0; // declaration of two integer type variables
clrscr();
printf("\nEnter an expression");
scanf("%s", expression);
// Scanning the expression until we reach the end
while(expression[i]!= '\0')
{
//to check the symbol is '('
if(expression[i]=='(')
{
x++; // incrementing 'x' variable
}
else if(expression[i]==')') // condition to check the symbol is ')'
{
x--; // decrementing 'x' variable
if(x<0)
break;
}
i++; // incrementing 'i' variable.
}
// Condition to check whether x is equal to 0 or not.
if(x==0)
{
printf("Expression is balanced");
}
else
{ 27
printf("Expression is unbalanced");
}
getch();
}
Output:
Result:
Thus the c program for balancing parenthesis is implemented and the output has been
verified.
28
Ex No: 4.b IMPLEMENTATION OF STACK APPLICATION
Date : (Infix to Postfix Expression Conversion)
Aim:
Algorithm:
➢ Check the precedence of the operator in the stack which is in the stack has greater
precedence than the precedence of the operator read, if so then remove that
symbol from the stack and place in the postfix expression.
➢ Repeat the step 6 till the operator in the stack has greater precedence than the
• If the input symbol read is a closing parenthesis ‘)’ then pop all operators from the
stack, place them in postfix expression till the opening parenthesis ‘(‘ is not popped.
• The ‘(‘ should not be placed in the postfix expression.
29
Program:
// Infix to Postfix Expression Conversion
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>#define N 64
#define LP 10
#define RP 20
#define OPERATOR 30
#define OPERAND 40
#define LPP 0
#define AP 1 #define
SP AP #define MP 2
#define DP MP
#define REMP 2
#define NONE 9
do
{
30
top=-1;
}
void infixtopostfix(void)
{
int i,p,l,type,prec;char
next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP: push(infix[i]);
break;
31
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
} i++;
}
while(top>-1) postfix[p++]=pop();
postfix[p]='\0';
}
int gettype(char sym)
{
switch(sym)
{
case '(':
return(LP);case ')':
return(RP);
case '+':
case '-':
case'*':
case '/':
case '%': return(OPERATOR);
default : return(OPERAND);
}
}
void push(char sym)
{
if(top>N)
{
printf("\nStack is full\n");
exit(0);
}
32
else
stack[++top]=sym;
}
char pop(void)
{
if(top<=-1)
{
printf("\nStack is empty\n");
exit(0);
}
else
return(stack[top--]);
return ' ';
}
int getprec(char sym)
{
switch(sym)
{
case '(':
return(LPP);
case '+':
return(AP);
case '-':
return(SP);
case '*':
return(MP);
case '/':
return(DP);
case '%':
return(REMP);
default :
return(NONE);
33
}
Output:
Result:
Thus the program for conversion of infix to postfix expression using stack hasbeen
done and the output has been verified.
34
Exp No: 5.a IMPLEMENTATION OF QUEUE APPLICTION
Date : (First Come First Serve CPU Scheduling)
Aim:
To write a c program to implement First Come First Serve CPU scheduling using queue.
Algorithm:
1. Start
2. Declare the array size
3. Read the number of processes to be inserted
4. Read the Burst times of processes
5. Calculate the waiting time of each process
wt[i+1]=bt[i]+wt[i]
6. Calculate the turnaround time of each processtt[i+1]=tt[i]+bt[i+1]
7. Calculate the average waiting time and average turnaround time.
8. Display the values
9. Stop
35
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,bt[10],n,wt[10],tt[10],w1=0,t1=0;
float aw,at;clrscr();
printf("enter no. of processes:\n");
scanf("%d",&n);
printf("enter the burst time of processes:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
for(i=0;i<n;i++)
{
wt[0]=0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1]; w1=w1+wt[i]; t1=t1+tt[i];
}
aw=w1/n; at=t1/n;
printf("\nbt\t wt\t tt\n");
for(i=0;i<n;i++)
printf("%d\t %d\t %d\n",bt[i],wt[i],tt[i]);
printf("aw=%f\n,at=%f\n",aw,at); getch();
}
36
Output:
Result:
Thus the program to implement First Come First Serve CPU scheduling algorithm using queue
has been done and the output has been verified.
37
Exp No: 5.b IMPLEMENTATION OF QUEUE APPLICTION
Date : (Round Robin CPU Scheduling)
Aim:
Algorithm:
1. Start
2. Declare the array size
3. Read the number of processes to be inserted
4. Read the burst times of the processes
5. Read the Time Quantum
6. if the burst time of a process is greater than time Quantum then subtract time quantum form the
burst time Else Assign the burst time to time quantum.
7. Calculate the average waiting time and turnaround time of the processes.
8. Display the values
9. Stop
38
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int st[10],bt[10],wt[10],tat[10],n,tq; int i,count=0,swt=0,stat=0,temp,sq=0; float awt=0.0,atat=0.0;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]); st[i]=bt[i];
}
printf("Enter time quantum:");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq; if(st[i]==0)
{
count++;
continue;
}
if(st[i]>tq)
st[i]=st[i]-tq;
else if(st[i]>=0)
{
temp=st[i]; st[i]=0;
}
sq=sq+temp; tat[i]=sq;
39
}
if(n==count)
break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("Process_no Burst time Wait time Turn around time");
for(i=0;i<n;i++)
printf("\n%d\t %d\t %d\t %d",i+1,bt[i],wt[i],tat[i]);
printf("\nAvg wait time is %f Avg turn around time is %f",awt,atat);
getch();
}
40
Output:
Result:
Thus the program to implement Round Robin CPU scheduling algorithm using queue has been
done and the output has been verified
41
Exp No: 6 IMPLEMENTATION OF PRIORITY QUEUE
Date : (Binary Heap)
Aim:
To build a binary heap from an array of input elements to implement priority queue.
Algorithm:
1. Start
2. In a heap, for every node x with parent p, the key in p is smaller than or equal to the key in
x.
3. For insertion operation
a. Add the element to the bottom level of the heap.
b. Compare the added element with its parent; if they are in the correct order,
stop.
c. If not, swap the element with its parent and return to the previous step.
5. Stop
42
Program:
/* Binary Heap */
#include <stdio.h>
#include<conio.h>
#include <limits.h>
int heap[100], heapSize;
void Init()
{
heapSize = 0;
heap[0] = -INT_MAX;
}
void Insert(int element)
{
int now = heapSize;
heapSize++;
heap[heapSize] = element;
while (heap[now / 2] > element)
{
heap[now] = heap[now / 2];
now /= 2;
}
heap[now] = element;
}
int DeleteMin()
{
int minElement, lastElement, child, now;
minElement = heap[1];
lastElement = heap[heapSize--];
for (now = 1; now * 2 <= heapSize; now = child)
{
child = now * 2;
if (child != heapSize && heap[child + 1] < heap[child])
43
child++;
if (lastElement > heap[child])
heap[now] = heap[child];
else
break;
}
heap[now] = lastElement;
return minElement;
}
void main()
{
int number_of_elements;
int iter, element;
clrscr();
printf("Program to demonstrate Heap:\nEnter the number of elements: ");
scanf("%d", &number_of_elements);
Init();
printf("Enter the elements: ");
for (iter = 0; iter < number_of_elements; iter++)
{
scanf("%d", &element); Insert(element);
}
for (iter = 0; iter < number_of_elements; iter++)
printf("%d ", DeleteMin());
printf("\n");
getch();
}
44
Output:
2 3 4 5 15 45
Result:
Thus a binary heap is constructed for the given elements to implement priority queue.
45
Exp No: 7 IMPLEMENTATION OF BINARY SEARCH TREE
Date :
Aim:
To write a C program to implement binary search tree.
Algorithm:
1. Start the program.
2. Initialise and declare the variable, and read the binary search tree operations.
3. If operation is Create then process the following steps.
• Read the data.
• Memory is to be allocated for the new node.
• The data field of the new node is then stored with the information read from the user.
• The link field is assigned to null.
4. If operation is Insertion do the following steps.
• Check the root node of the binary search tree is null.
• If the condition is true, the new node as the root node.
• Otherwise follow the next steps.
• Compare the new node data with root node data for the following two conditions:
a. If the new node data is less than the root node data, traverse the left subtree
recursively until it reaches left is NULL. Left is assigned to new node.
b. If the new node is greater than the root node data, traverse the right sub tree
recursively until it reaches right is NULL. Right is assigned to new node.
5. If operation is display then, traverse through elements in order to print theelement.
6. If operation is searching an element do the following steps.
• Get data to be searched.
• Check whether the root is null to return the NULL value. Otherwise check the data with the
root node.
• If the data is lesser than the root, then go left as long as there is a left child.
• If the data is greater than the root, then go right as long as there is a right child
47
printf("5.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("\n\t\t\tBinary tree creation\n");
printf("Enter the data<0 to stop>:");
scanf("%d",&element);
link=(tree*)malloc(sizeof(tree));
link->data=element;
link->right=NULL;
link->left=NULL;
root=link;
scanf("%d",&element);
while(element!=0)
{
addnode(root,element);
scanf("%d",&element);
}
break;
48
printf("\nEnter
the element to
be search: ");
49
scanf("%d",&key);
temp=search(root,key,&parent);
if(temp==root)
printf("\nThe element %d is the root. \n",temp->data);
else if(key!=temp->data)
printf("\nThe element does not exists. \n");
else
printf("\nParent of node %d is %d. \n",temp->data,parent->data);
break;
case 5:
exit();
break;
}
getch();
}
}
void display(tree *t,int lm,int rm,int l)
{
if(t!=NULL)
{
x=(lm+rm)/2;
gotoxy(x,4*l);
printf("%d\n\n",t->data);
gotoxy(35, 25);
display(t->left,lm,x+l2,l+1);
display(t->right,x-4,rm,l+1);
}
}
tree *addnode(tree *node,int info)
{
50
if(node==NULL)
51
{
52
node=(tree*)malloc(sizeof(tree));
node->data=info;
node->left=NULL;
node->right=NULL;
return node;
}
else
{
if(node->data==info)
{
printf("\nData already exists. \n");
return node;
}
else
{
if(node->data>info)
{
node->left=addnode(node->left,info);
return node;
}
else
{
node->right=addnode(node->right,info);
return node;
}
}
}
}
tree *search(tree *root,int key,tree **parent)
{
tree *temp;
temp=root;
53
while(temp!=NULL)
{
if(temp->data==key)
{
printf("\nThe element %d is present \n",temp->data);
return temp;
}
*parent=temp;
if(temp->data>key)
temp=temp->left;
else
temp=temp->right;
}
return NULL;
}
Output:
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:1
BINARY SEARCH
1.Creation
2.Insertion
54
3. Display
4. Searching an element
5.Exit
Enter your choice:3
10
6 15
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
55
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:3
10
6 15
56
2 11
4 13
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
57
Parent of node 6 is 10.
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4. Searching an
element5.Exit
Enter your choice:4
Enter the element to be search: 40
Result:
Thus the operations of binary search tree have been implemented successfully in C program.
58
EXP NO: 7 IMPLEMENTATION OF INSERTION IN AVL TREE
DATE :
Aim:
To write a C program to implement insertion in AVL tree.
Algorithm:
1. Start the program.
2. Declare the structure of binary search in tree.
3. Read the elements to be inserted into the tree.
4. Find the place to insert the new node in the tree.
5. Find the balance factor for all nodes. Check it is a balanced tree (balance factor: -1, 0 , +1)
• To insert another element, compare the new node data with root node data. If the new
node data is less than the root node data, traverse the left subtree recursively until it reaches
left is NULL. Otherwise traverse the right sub tree recursively until it reaches right is
NULL.
• Find the balance factor for all nodes. Check it is a balanced tree (balance factor: -1, 0 ,
+1).
• If it is a balanced tree, terminate the process.
59
7. Compute the balancing factor for all nodes. Check it is a balanced tree (balance factor: -1, 0
, +1). If it is a balanced tree.
Program:
// Implementation of insertion in AVL tree
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define FALSE 0
#define TRUE 1
struct AVLNode
{
int data ;
int balfact ;
struct AVLNode *left ;
struct AVLNode *right ;
};
struct AVLNode * buildtree ( struct AVLNode *, int, int * ) ;
struct AVLNode * balright ( struct AVLNode *, int * ) ;
struct AVLNode * balleft ( struct AVLNode *, int * ) ;
void display ( struct AVLNode * ) ;
void main( )
{
struct AVLNode *avl = NULL ;
int h,i,num,n;
clrscr( ) ;
printf("Enter the number of elements");
scanf("%d",&n);
60
for(i=0;i<n;i++)
{
scanf("%d",&num);
avl = buildtree ( avl, num, &h ) ;
}
printf ( "\nAVL tree:\n" ) ;
display ( avl ) ;
getch( ) ;
}
61
case 1:
node1 = root -> left ;
if ( node1 -> balfact == 1 )
{
printf ( "\nRight rotation along %d.", root -> data ) ;
root -> left = node1 -> right ;
node1 -> right = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
printf ( "\nDouble rotation, left along %d",node1 -> data ) ;
node2 = node1 -> right ;
node1 -> right = node2 -> left ;
printf ( " then right along %d.\n", root -> data ) ;
node2 -> left = node1 ;
root -> left = node2 -> right ;
node2 -> right = root ;
if ( node2 -> balfact == 1 )
root -> balfact = -1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == -1 )
node1 -> balfact = 1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
break ;
62
case 0:
root -> balfact = 1 ;
break ;
case -1:
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
63
root -> right = node1 -> left ;
node1 -> left = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
printf ( "\nDouble rotation, right along %d",node1 -> data ) ;
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
printf ( " then left along %d.\n", root -> data ) ;
root -> right = node2 -> left ;
node2 -> left = root ;
if ( node2 -> balfact == -1 )
root -> balfact = 1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == 1 )
node1 -> balfact = -1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
return ( root ) ;
}
64
/* balances the tree, if right sub-tree is higher */
struct AVLNode * balright ( struct AVLNode *root, int *h )
{
struct AVLNode *node1, *node2 ;
switch ( root -> balfact )
{
case 1:
root -> balfact = 0 ;
break;
case 0:
root -> balfact = -1 ;
*h = FALSE ;
break;
case -1:
node1 = root -> right ;
if ( node1 -> balfact <= 0 )
{
printf ( "\nLeft rotation along %d.", root -> data ) ;
root -> right = node1 -> left ;
node1 -> left = root ;
if ( node1 -> balfact == 0 )
{
root -> balfact = -1 ;
node1 -> balfact = 1 ;
*h = FALSE ;
}
else
{
root -> balfact = node1 -> balfact = 0 ;
}
65
root = node1 ;
}
else
{
printf ( "\nDouble rotation, right along %d", node1 -> data );
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
printf ( " then left along %d.\n", root -> data );
root -> right = node2 -> left ;
node2 -> left = root ;
66
{
case -1:
root -> balfact = 0 ;
break ;
case 0:
root -> balfact = 1 ;
*h = FALSE ;
break ;
case 1:
node1 = root -> left ;
if ( node1 -> balfact >= 0 )
{
printf ( "\nRight rotation along %d.", root -> data ) ;
root -> left = node1 -> right ;
node1 -> right = root ;
if ( node1 -> balfact == 0 )
{
root -> balfact = 1 ;
node1 -> balfact = -1 ;
*h = FALSE ;
}
else
{
root -> balfact = node1 -> balfact = 0 ;
}
root = node1 ;
}
else
{
printf ( "\nDouble rotation, left along %d", node1 -> data ) ;
node2 = node1 -> right ;
67
node1 -> right = node2 -> left ;
node2 -> left = node1 ;
printf ( " then right along %d.\n", root -> data ) ;
root -> left = node2 -> right ;
node2 -> right = root ;
68
Output:
Result:
Thus the insertion in AVL tree has been implemented successfully in C program.
69
Exp No: 9.a IMPLEMENTATION OF BREADTH FIRST SEARCH
Date :
Aim
To create adjacency matrix of the given graph and to perform breadth first search
traversal.
Algorithm
1. Start
2. Obtain Adjacency matrix for the given graph
3. Define a Queue of size total number of vertices in the graph.
4. Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
5. Visit all the adjacent vertices of the verex which is at front of the Queue which is not
visited and insert them into the Queue.
6. When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex from the Queue.
7. Repeat step 5 and 6 until queue becomes empty.
8. When queue becomes Empty, then produce final spanning tree by removing unused
edges from the graph.
9. Stop
70
Program:
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
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;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++)
if(visited[i])
71
printf("%d\t",i); else
printf("\n Bfs is not possible");
getch();
}
Output:
Result:
Thus Breadth First Traversal is executed on the given graph.
72
Exp No: 9.b IMPLEMENTATION OF DEPTH FIRST SEARCH
Date :
Aim:
To create adjacency matrix of the given graph and to perform depth first search traversal.
Algorithm:
1. Start
2. Obtain Adjacency matrix for the given graph
3. Create a recursive function that takes the index of the node and a visited array.
4. Mark the current node as visited and print the node.
5. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of
the adjacent node.
6. Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous
DFS, call the recursive function with the current node.
73
Program:
#include<stdio.h>
#include<conio.h>
int a[20][20],reach[20],n;
void dfs(int v) {
int i;
reach[v]=1;
for (i=1;i<=n;i++)
if(a[v][i] && !reach[i]) {
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main() {
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++)
{
if(reach[i])
74
count++;
}
if(count==n)
printf("\n Graph is connected"); else
printf("\n Graph is not connected");
getch();
}
Output :
75
Result:
Thus depth first traversal is executed on the given undirected graph.
76