Data Structure Lab Manual
Data Structure Lab Manual
INDEX
S.No TOPICS PAGE NO
1a ARRAY IMPLEMENTATION OF STACK 3
1b ARRAY IMPLEMENTATION OF QUEUE 6
2 ARRAY IMPLEMENTATION OF LIST 9
3a LINKED LIST IMPLEMENTATION OF LIST
13
[SINGLY LINKED LIST]
3b LINKED LIST IMPLEMENTATION OF STACK 16
3c LINKED LIST IMPLEMENTATION OF QUEUE 19
4a APPLICATIONS OF LIST POLYNOMIAL
22
ADDITION AND SUBTRACTION
4b INFIX TO POSTFIX 28
4c EXPRESSION EVALUATION 32
5 IMPLEMENTATION OF BINARY SEARCH
34
TREES
6 IMPLEMENTATION OF AVL TREES 41
7 IMPLEMENTATION OF HEAP USING PRIORITY
47
QUEUES
8a REPRESENTATION OF GRAPH 53
8b GRAPH TRAVERSAL-BREADTH FIRST
55
TRAVERSAL
8c GRAPH TRAVERSAL-DEPTH FIRST
59
TRAVERSAL
9a LINEAR SEARCH 61
9b BINARY SEARCH 63
10a INSERTION SORT 65
10b BUBBLE SORT 67
10c QUICK SORT 69
10d MERGE SORT 71
11 ADDITIONAL EXPERIMENT (CONTENT
BEYOND SYLLABUS)- IMPLEMENTATION OF 74
HASH FUNCTIONS AND
COLLISION RESOLUTION TECHNIQUE
12 VIVA QUESTIONS 78
2
Algorithm
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. If top < max -1
8. Increment top
9. Store element at current position of top
10. Else
11. Print Stack overflow
12. If choice = 2 then
13. If top < 0 then
14. Print Stack underflow
15. Else
16. Display current top element
17. Decrement top
18. If choice = 3 then
19. Display stack elements starting from top
20. Stop
Program
/* 1a - Stack Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5 static
int stack[max]; int
top = -1; void
push(int x)
3
{ stack[++top] = x;
} int
pop()
{ return (stack[top--]);
} void
view()
{
int i;
if (top < 0) printf("\n Stack Empty \
n");
else
{ printf("\n Top-->");
for(i=top; i>=0; i--)
{ printf("%4d", stack[i]);
} printf("\
n");
}
}
main()
{ int ch=0, val;
clrscr();
while(ch != 4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch) { case 1:
if(top < max-1)
{ printf("\nEnter Stack element : ");
scanf("%d", &val);
push(val);
} else printf("\n Stack Overflow \n");
break;
case 2:
if(top < 0) printf("\n Stack Underflow \
n");
else
{ val = pop();
printf("\n Popped element is %d\n", val);
}
break;
case 3: view();
break;
case 4:
4
exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
Output
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 23
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 34
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 45
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 45 34 23 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2
Popped element is 45
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 34 23 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 4
Result: Thus push and pop operations of a stack was demonstrated using arrays.
5
Algorithm
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
7. If rear < max -1
8. Increment rear
9. Store element at current position of rear
10. Else
11. Print Queue Full
12. If choice = 2 then
13. If front = –1 then
14. Print Queue empty
15. Else
16. Display current front element
17. Increment front
18. If choice = 3 then
19. Display queue elements starting from front to rear.
20. Stop
Program
/* 1b - Queue Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5 static
int queue[max]; int
front = -1; int rear = -
1; void insert(int x)
{ queue[++rear] = x; if
(front == -1) front
= 0;
} int
remove()
{
6
Output
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 12
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 23
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 34
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 45
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 56
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Queue Full
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 3
Front--> 12 23 34 45 56 <--Rear
Result: Thus insert and delete operations of a queue was demonstrated using arrays.
Algorithm
1. Start
2. Define list using an array of size n.
3. First item with subscript or position = 0
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create an empty location in array after the node by moving the existing elements one
position ahead.
9. Insert the new element at appropriate position
10. Else if choice = 2
11. Get element to be deleted.
12. Locate the position of the element replace the element with the element in the following
position.
13. Repeat the step for successive elements until end of the array.
14. Else
15. Traverse the list from position or subscript 0 to n.
16. Stop
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()
{
//clrscr();
int ch;
char g='y';
do
{
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;
9
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]);
}
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--; }
10
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()
{ 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::\n");
scanf("%d",&p);
b[pos]=p;
n+
+; }
printf("\n The list after insertion::\n");
display();
}
void display()
{ printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{ printf("\n\n%d", b[i]);
}
11
Output
Array of 10 numbers:
Input elements:
1
2
4
5
6
7
8
9
10
11
Current array: 1 2 4 5 6 7 8 9 10 11
Would you like to enter another element? [1/0]: 1
Input element: 3
Input position: 2
Current array: 1 2 3 4 5 6 7 8 9 10
Aim: To define a singly linked list node and perform operations such as insertions and deletions
dynamically.
Algorithm
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
9. Insert the new node at appropriate position by manipulating address
10. Else if choice = 2
11. Get node's data to be deleted.
12. Locate the node and delink the node
12
Program
/* 3c - Single Linked List */
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h>
struct node
{
int label; struct
node *next;
};
main()
{
int ch, fou=0;
int k;
struct node *h, *temp, *head,
*h1; /* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->label = -1; head->next = NULL;
while(-1)
{ clrscr(
);
printf("\n\n
SINGLY
LINKED
LIST
OPERATI
ONS \n");
printf("1-
>Add ");
printf("2-
>Delete ");
printf("3-
>View ");
printf("4-
>Exit \n");
printf("Ente
r your
choice : ");
scanf("%d",
&ch);
switch(ch)
{
13
{ fou=1;
break; }
h = h->next;
}
if (h->label == k)
fou = 1;
if (fou != 1)
printf("Node not found\n");
else
{
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d" , &temp->label); temp-
>next = h->next;
h->next = temp;
}
break;
}
break;
Output
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label after which new node is to be added : -1
Enter label for new node : 23
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label after which new node is to be added : 23
Enter label for new node : 67
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 23 -> 67 -> NULL
Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
15
Program
/* 5c - Stack using Single Linked List */
#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 : "); 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:
16
Output
Result: Thus push and pop operations of a stack was demonstrated using linked list.
17
Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
11. Make temp node point to first node
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
15. Display stack elements starting from head node till null
16. Stop
18
Program
/* 3c - Queue using Single Linked List */
#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 Queue using Linked List \n");
printf("1->Insert "); printf("2-
>Delete "); 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 : "); scanf("%d",
&temp->label); /* Reorganize the links */ h =
head; while (h->next != NULL) h = h->next;
h->next = temp; temp->next
= NULL;
break;
case 2:
/* Delink the first node */ h
= head->next; head->next
= h->next; printf("Node
deleted \n");
free(h);
break;
case 3: printf("\n\nHEAD -> ");
h=head;
while (h->next!=NULL)
{ h = h->next;
printf("%d -> ",h->label);
} printf("NULL \
n"); break;
case 4: exit(0);
19
}
}
}
Output
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 12
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 12 -> 23 -> NULL
Result: Thus push and pop operations of a stack was demonstrated using linked list.
20
Aim: To store a polynomial using linked list. Also, perform addition and subtraction on two
polynomials.
Algorithm
Let p and q be the two polynomials represented by linked lists 1.
while p and q are not null, repeat step 2.
2. If powers of the two terms are equal then
If the terms do not cancel then
Insert the sum of the terms into the sum Polynomial
Advance p Advance q
Else if the power of the first polynomial> power of second Then
Insert the term from first polynomial into sum polynomial
Advance p
Else insert the term from second polynomial into sum polynomial Advance q
3. Copy the remaining terms from the non empty polynomial into the sum polynomial. The
third step of the algorithm is to be processed till the end of the polynomials has not been
reached.
Program
/* 4a – Polynomial Addition and Subtraction */
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct node
{
int num;
int coeff; struct
node *next;
};
21
struct node *add_poly(struct node *start1, struct node *start2, struct node *start3)
{ struct node *ptr1, *ptr2;
int sum_num, c; ptr1 =
start1, ptr2 = start2;
while(ptr1 != NULL && ptr2 != NULL)
{ if(ptr1 ->coeff == ptr2 ->coeff)
{
sum_num = ptr1 ->num + ptr2 ->num; start3 =
add_node(start3, sum_num, ptr1 ->coeff);
23
struct node *sub_poly(struct node *start1, struct node *start2, struct node *start4)
{ struct node *ptr1, *ptr2; int
sub_num, c; ptr1 = start1,
ptr2 = start2; do
{ if(ptr1 ->coeff == ptr2 ->coeff)
{ sub_num = ptr1 ->num – ptr2 ->num;
start4 = add_node(start4, sub_num, ptr1 ->coeff); ptr1
= ptr1 ->next; ptr2 = ptr2 ->next;
}
else if(ptr1 ->coeff > ptr2 ->coeff)
{ start4 = add_node(start4, ptr1 ->num, ptr1 ->coeff); ptr1
= ptr1 ->next;
}
else if(ptr1 ->coeff < ptr2 ->coeff)
{ start4 = add_node(start4, ptr2 ->num, ptr2 ->coeff); ptr2
= ptr2 ->next;
}
}while(ptr1 != NULL || ptr2 != NULL); if(ptr1
== NULL)
{ while(ptr2 != NULL)
{ start4 = add_node(start4, ptr2 ->num, ptr2 ->coeff); ptr2
= ptr2 ->next;
24
}
}
if(ptr2 == NULL)
{ while(ptr1 != NULL)
{ start4 = add_node(start4, ptr1 ->num, ptr1 ->coeff); ptr1
= ptr1 ->next;
}
}
return start4;
}
Output
******* MAIN MENU *******
1. Enter the 1rst polynomial
2. Display the 1rst polynomial
–––––––––––––––––––––––––––––––
9. EXIT
Enter your option : 1
Enter the number : 6
Enter its coef cient : 2
Enter the number : 5
Enter its coef cient : 1
Enter the number : –1
Enter your option : 2
6x25x1
Enter your option : 9
25
Aim: To convert infix expression to its postfix form using stack operations.
Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator‟s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the inputoperator, Pop it from the
stack and print it.
9. Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
12. If the character is a right parenthesis, pop all the operators from the stack andprint it until a
left parenthesis is encountered. Do not print the parenthesis.
Program
26
{ if(symbol == '(')
push(symbol);
else if(symbol == ')')
{ while(stack[top] != '(')
{ postfix[j] = pop(); j+
+; } pop(); //pop out (.
}
else
{ if(p
rcd(s
ymb
ol) >
prcd(
stack
[top]
))
push(
symb
ol);
else
{ while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop(); j+
+;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{ postfix[j] = pop(); j+
+; }
postfix[j] = '\0';
}
main()
{ char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix); convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix); getch(); }
void push(char item)
{ top++; stack[top] =
item;
}
char pop()
28
{ char a; a =
stack[top];
top--; return a;
}
Output
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/
Enter the valid infix string: a*b+c*d/e
The corresponding postfix string is: ab*cd*e/+
Enter the valid infix string: a+b*c+(d*e+f)*g
The corresponding postfix string is: abc*+de*f+g*+
Result: Thus the given infix expression was converted into postfix form using stack.
29
Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
5. If character is an operand push it onto the stack
6. If character is an operator
7. Pop topmost two elements from stack.
8. Apply operator on the elements and push the result onto the stack, Eventually only result will
be in the stack at end of the expression.
9. Pop the result and print it.
Program
/* Evaluation of Postfix expression using stack */
#include <stdio.h>
#include <conio.h>
struct stack
{ int top; float
a[50];
}s; main()
{ char pf[50]; float
d1,d2,d3;
int i;
clrscr();
s.top = -1; printf("\n\n Enter the postfix
expression: "); gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{ case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] = pf[i]-'0';
break;
case '+':
30
d1 = s.a[s.top--];
d2 = s.a[s.top--];
s.a[++s.top] = d1 + d2;
break; case '-':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1 - d2;
break;
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1*d2;
break; case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1 / d2;
break;
}
}
printf("\n Expression value is %5.2f", s.a[s.top]);
getch();
}
Output
Enter the postfix expression: 6523+8*+3+*
Expression value is 288.00
Result: Thus the given postfix expression was evaluated using stack.
Algorithm
1. Start
2. Call insert to insert an element into binary search tree.
3. Call delete to delete an element from binary search tree.
4. Call findmax to find the element with maximum value in binary search tree
5. Call findmin to find the element with minimum value in binary search tree
6. Call find to check the presence of the element in the binary search tree 7. Call display to
display the elements of the binary search tree
8. Call makeempty to delete the entire tree.
9. Stop
Insert function
1. Get the element to be inserted.
2. Find the position in the tree where the element to be inserted by checking the
elements in the tree by traversing from the root.
3. If the element to be inserted is less than the element in the current node in
the tree then traverse left subtree
4. If the element to be inserted is greater than the element in the current node in
the tree then traverse right subtree
5. Insert the element if there is no further move
Delete function
1. Get the element to be deleted.
2. Find the node in the tree that contain the element.
3. Delete the node an rearrange the left and right siblings if any present for the
deleted node
Findmax function
1. Traverse the tree from the root.
2. Find the rightmost leaf node of the entire tree and return it
3. If the tree is empty return null.
Findmin function
1. Traverse the tree from the root.
2. Find the leftmost leaf node of the entire tree and return it
3. If the tree is empty return null.
Find function
1. Traverse the tree from the root.
2. Check whether the element to searched matches with element of the current node.
If match occurs return it.
3. Otherwise if the element is less than that of the element of the current node then
search the leaf subtree
4. Else search right subtree.
Makeempty function
Make the root of the tree to point to null.
32
Program
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct searchtree
{ int element;
struct searchtree *left,*right;
}*root; typedef struct searchtree
*node; typedef int ElementType;
node insert(ElementType, node);
node delete(ElementType, node);
void makeempty(); node
findmin(node); node
findmax(node); node
find(ElementType, node); void
display(node, int);
void main()
{ int ch;
ElementType a; node
temp; makeempty();
while(1)
{ printf("\n1. Insert\n2. Delete\n3. Find\n4. Find min\n5. Find max\n6.Display\n7.
Exit\nEnter Your Choice : "); scanf("%d",&ch); switch(ch)
{ case 1:
printf("Enter an element : ");
scanf("%d", &a); root
= insert(a, root);
break;
case 2:
printf("\nEnter the element to delete : ");
scanf("%d",&a); root
= delete(a, root);
break;
case 3:
printf("\nEnter the element to search : ");
scanf("%d",&a); temp =
find(a, root); if (temp !=
NULL) printf("Element
found"); else
printf("Element not found");
break;
case 4:
temp = findmin(root);
if(temp==NULL)
printf("\nEmpty tree");
else
printf("\nMinimum element : %d", temp->element); break;
case 5:
33
temp = findmax(root);
if(temp==NULL)
printf("\nEmpty tree");
else
printf("\nMaximum element : %d", temp->element); break;
case 6: if(root==NULL)printf("\nEmpty
tree");
else
display(root, 1);
break;
case 7: exit(0); default:
printf("Invalid Choice");
}
}
}
free (temp);
} else
{ temp = t; t=t->left;
free (temp);
}
}}
return t;
}
void makeempty()
{ root = NULL;
}
Sample Output:
35
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display 7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 3
36
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 7
37
Result:
The program for binary search tree is executed and verified.
Insert operation may cause balance factor to become 2 or –2 for some node
› only nodes on the path from insertion point to root node have possibly changed in height
› So after the Insert, go back up to the root node by node, updating heights
› If a new balance factor (the difference hleft – hright ) is 2 or –2, adjust tree by rotation
around the node
Let the node that needs rebalancing be α.
There are 4 cases:
Outside Cases (require single rotation) :
38
DOUBLE ROTATION
DoubleRotateFromRight(n : reference node pointer)
{
RotateFromLeft(n.right);
RotateFromRight(n);
}
DELETION
Similar but more complex than insertion
› Rotations and double rotations needed to rebalance
› Imbalance may propagate upward so that many rotations may be needed.
Program
// C program to insert a node in AVL tree
#include<stdio.h>
#include<stdlib.h>
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct Node* newNode(int key)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->key = key; node-
>left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
40
// Perform rotation y-
>left = x;
x->right = T2;
return node;
}
OUTPUT
The constructed AVL Tree would be
43
Algorithm
• Thus, a max-priority queue returns the element with maximum key first
whereas, a min-priority queue returns the element with the smallest key first.
• Priority queues are used in many algorithms like Huffman Codes, Prim's
algorithm, etc. It is also used in scheduling processes for a computer, etc.
44
• Heaps are great for implementing a priority queue because of the largest and
smallest element at the root of the tree for a max-heap and a minheap
respectively. We use a max-heap for a max-priority queue and a min-heap
for a min-priority queue.
• This is like the pop of a queue, we return the element as well as delete it
from the heap. So, we have to return and delete the root of a heap. Firstly,
we store the value of the root in a variable to return it later from the
function and then we just make the root equal to the last element of the
heap. Now the root is equal to the last element of the heap, we delete the
last element easily by reducing the size of the heap by 1.
• Doing this, we have disturbed the heap property of the root but we have not
touched any of its children, so they are still heaps. So, we can call Heapify
on the root to make the tree a heap again.
EXTRACT-MAXIMUM(A)
Program
#include <stdio.h>
print_heap(A);
increase_key(A, 5, 22);
print_heap(A);
decrease_key(A, 1, 13);
print_heap(A);
48
printf("%d\n\n", maximum(A));
printf("%d\n\n", extract_max(A));
print_heap(A);
OUTPUT
RESULT:
Thus the implementation heap using priority queue was demonstrated.
49
Algorithm
For a graph with |V| vertices, an adjacency matrix is a |V|× V matrix of 0s and 1s,
where the entry in row i and column j is 1 if and only if the edge (i,j) in the graph.
1. Consider the graph to be represented
2. Start from an edge
3. If the edge connects the vertices i,j the mark the ith row and jth column of the adjacency matrix
as 1 otherwise store 0 4. Finally print the adjacency matrix
Program
#include<stdio.h>
#define V 5
init(adjMatrix);
addEdge(adjMatrix,0,1);
addEdge(adjMatrix,0,2);
addEdge(adjMatrix,0,3);
addEdge(adjMatrix,1,3);
addEdge(adjMatrix,1,4);
addEdge(adjMatrix,2,3);
addEdge(adjMatrix,3,4);
printAdjMatrix(adjMatrix);
return 0; }
OUTPUT
01110
00011
00010
00001
00000
51
Algorithm
BFS (G, s) //Where G is the graph and s is the source node
let Q be queue.
Q.enqueue( s ) //Inserting s in queue until all its neighbour vertices are marked.
mark s as visited.
while ( Q is not empty)
//Removing that vertex from queue,whose neighbour will be visited now
v = Q.dequeue( )
Program
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
struct Vertex {
char label;
bool visited;
};
//queue variables
int queue[MAX];
int rear = -1;
52
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//queue functions
int removeData()
{ queueItemCount--;
return queue[front++];
}
bool isQueueEmpty()
{ return queueItemCount ==
0;
}
//graph functions
return -1;
}
void breadthFirstSearch() {
int i;
while(!isQueueEmpty()) {
//get the unvisited vertex of vertex which is at front of the queue
int tempVertex = removeData();
int main()
{ int i, j;
54
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4
addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D
breadthFirstSearch();
return 0;
}
Output
Breadth First Search: S A B C D
Result : Thus the graph using breadth first search traversal was demonstrated.
55
Algorithm
Program
#include<stdio.h>
void main()
{
int i,j;
printf("Enter number of vertices:");
56
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
57
Result : Thus the graph using depth first search traversal was demonstrated.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search 7. If Ai = search then found = 1 Print "Element
found"
Print position i Stop
8. If found = 0 then print
"Element not found"
Stop
Program
/* Linear search on a sorted array */
#include <stdio.h>
#include <conio.h>
main()
{ int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n); printf("Enter Array
Elements : \n"); for(i=0; i<n; i++)
scanf("%d", &a[i]); printf("Enter
element to locate : ");
scanf("%d", &val);
found = 0; for(i=0;
i<n; i++)
{ if (a[i] == val)
{ printf("Element found at position %d", i);
found = 1; break;
}
58
} if (found == 0) printf("\n
Element not found"); getch();
}
Output
Enter number of elements : 7
Enter Array Elements :
23 6 12 5 0 32 10
Enter element to locate : 5
Element found at position 3
Result
Thus an array was linearly searched for an element's existence.
59
Aim
To locate an element in a sorted array using Binary search method
Algorithm
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
a. Determine middle element mid = (upper+lower)/2
b. If key = arr[mid] then
i. Print mid
ii. Stop
c. Else if key > arr[mid] then
i. lower = mid + 1
d. else
i. upper = mid – 1
7. Print "Element not found"
8. Stop
Program
/* Binary Search on a sorted array */
#include <stdio.h>
void main()
{ int a[50],i, n, upper, lower, mid, val, found, att=0;
printf("Enter array size : "); scanf("%d", &n);
for(i=0; i<n; i++) a[i] = 2 * i; printf("\n Elements
in Sorted Order \n"); for(i=0; i<n; i++)
printf("%4d", a[i]); printf("\n Enter element to
locate : ");
scanf("%d", &val);
upper = n; lower = 0;
found = -1; while
(lower <= upper)
{ mid = (upper + lower)/2;
att++; if (a[mid]
== val)
{
printf("Found at index %d in %d attempts", mid, att);
found = 1; break; } else if(a[mid] > val) upper = mid - 1;
else lower = mid + 1;
60
} if (found == -1)
printf("Element not found");
}
Output
Enter array size : 10
Elements in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 16
Found at index 8 in 2 attempts
Result
Thus an element is located quickly using binary search method.
Algorithm
61
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer index i varies from second element to last element 5. Inner index j is used to compare
elements to left of outer index
6. Insert the element into the appropriate position.
7. Display the array elements after each pass 8.
Display the sorted array elements.
9. Stop
Program
/* 11a - Insertion Sort */
void main()
{ int i, j, k, n, temp, a[20], p=0;
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]);
}
Output
Enter total elements: 6
Enter array elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer Index i varies from last element to first element
a. Index j varies from first element to i-1
i. Compare elements Aj and Aj+1
63
Program
/* 11b - Bubble Sort */
#include <stdio.h>
main()
{ int n, t, i, j, k, a[20], p=0; printf("Enter total
numbers of elements: ");
scanf("%d", &n); printf("Enter
%d elements: ", n); for(i=0; i<n;
i++) scanf("%d", &a[i]);
for(i=n-1; i>=0; i--)
{ for(j=0; j<i; j++)
{ if(a[j] > a[j+1])
{ t = a[j]; a[j] =
a[j+1]; a[j+1]
= t;
}
} 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]);
}
Output
Enter total numbers of elements: 8
Enter 8 elements: 8 6 10 3 1 2 5 4
After Pass 1 : 6 8 3 1 2 5 4 10
After Pass 2 : 6 3 1 2 5 4 8 10
After Pass 3 : 3 1 2 5 4 6 8 10
After Pass 4 : 1 2 3 4 5 6 8 10
After Pass 5 : 1 2 3 4 5 6 8 10
After Pass 6 : 1 2 3 4 5 6 8 10
After Pass 7 : 1 2 3 4 5 6 8 10
Sorted List : 1 2 3 4 5 6 8 10
Result
Thus an array was sorted using bubble sort.
64
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. Display the sorted array elements
8. Stop
65
Program
/* 11c - Quick Sort */
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
main()
{ int arr[30];
int i, size;
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();
}
Output
Enter total no. of the elements : 8
Enter total 8 elements :
127
-1
04
66
-2
3
Quick sorted elements
-2 -1 0 1 2 3 4 7
Result
Thus the array was sorted using quick sort‟s divide and conquers method.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Display both sorted sub-arrays
7. Merge the sorted sub-arrays onto a single sorted array.
8. Display the merge sorted array elements
9. Stop
Program
/* 11d – Merge sort */
#include <stdio.h> #include
<conio.h> void merge(int
[],int ,int ,int ); void part(int
[],int ,int ); int size; main()
{ int i, arr[30];
67
} for(k=min; k<=max; k+
+) arr[k] = tmp[k];
}
Output
Enter total no. of elements : 8
Enter array elements : 24 13 26 1 2 27 38 15
Half sorted list : 1 13 24 26
Half sorted list : 2 15 27 38
Merge sorted list : 1 2 13 15 24 26 27 38
Result
Thus array elements was sorted using merge sort's divide and conquer method.
69
ADDITIONAL EXPERIMENT-
IMPLEMENTATION OF HASH FUNCTIONS
AND COLLISION RESOLUTION TECHNIQUE
Date:
Algorithm
1. Start
2. A structure that represent the key, data pair is created
3. Key is generated by hashcode function which returns the value of key%size where
size is assumed as 20
4. Insert function is called to insert a new key value pair into the hash table.
5. While inserting an element if the hashcode function returns a key that has been
previously assigned to an element in the hash table then a collision occurs.
6. If there is a collision then the hash key is incremented to move to the next place and
find whether there is a key-space for inserting the current element. This is called
collision resolution. This process is repeated until a space if found for current
element or the hash table is full
7. Delete function is called to delete an element from the hash table.
8. Stop
Program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20
struct DataItem
{ int data;
int key;
};
{
return key % SIZE;
}
return NULL;
}
void display()
{
int i = 0;
int main()
{
dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); dummyItem-
>data = -1;
dummyItem->key = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
display();
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
} else
{
printf("Element not found\n");
}
delete(item);
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
} else
72
{
printf("Element not found\n");
}
}
Output
~~ (1,20) (2,70) (42,80) (4,25) ~~ ~~ ~~ ~~ ~~ ~~ ~~ (12,44) (13,78)
(14,32) ~~ ~~ (17,11) (37,97) ~~
Element found: 97
Element not found
Result
The program for demonstrating hashing and collision resolution is executed and
verified.
73
VIVA QUESTIONS