Advanced Datastructures Lab Manual
Advanced Datastructures Lab Manual
EXERCISE-1:
AIM: To implement functions of Dictionary using Hashing ( Division method,
Multiplication method)
DESCRIPTION:-
Dictionary is a collection of data elements uniquely identified by a field called key.
A dictionary supports the operations of search,insert and delete.
A dictionary supports both sequential and random access.
These are useful in implementing symbol tables,text retrieval
systems,data base systems,etc.
Hash tables: “Hash table” is a data structure in which keys are mapped to array positions by
a hash function.
Hash function: A “Hash function” is simply a mathematical formula which when applied to
a key,produce an integer which can be used as an index for the key in the hash table.
Hashing:The process of mapping the keys to appropriate locations(or indexes) in a hash
table is called “Hashing”
There are different types of hash functions to calculate the hash value.They are
1.Division method
2.Multiplication method
5.Universal hashing
Division method:
It is the most simple method of hashing an integer x.This method divides x by M and then
uses the remainder that is obtained.The hash function can be given as
H(z)=z mod M
The division method is good for any value of M because it requires only a single division
method or operation .It works very fast.But care must be taken to select a suitable value for
M.
Generally it is best to choose M to be a prime number .
And M should also be not too close to the exact powers of 2.
1
ADVANCED DATASTRUCTURES LAB MANUAL
Code:
int const M=97; //prime value
int h(int x)
{
return(x%M);
}
Example:
calculate the hash values of keys 1234 and 5462 assume M=97.
h(1234)=1234%97=70
h(5462)=5462%97=16
Multiplication method:
The steps involved in multiplication method are as follows:
Step1: Choose a constant R such that 0<A<1.
Step2: Multiply the key K by A.
Step3: Extract the fractional part of KA.
Step4: Multiply the result of step3 by M and take the floor.
Hence the hash function can be given as
h(x)=[m(KA mod 1)]
where (KA mod 1) gives the fractional part of KA and M is the total number of indices in the
hash table.The greatest advantage of this method is that it works with any value of A. The
best choice of A is (sqrt-1)/2=0.61803398.
Example: Given a hash table of size 1000,map the key 12345 to an appropriate location in
the hash table.
Sol: We will use A=0.618033,m=1000,k=12345
h(12345)=[1000(12345*0.618033)]
=[1000(7629.617385 mod 1)]
=[1000(0.617385)]
=[617.385]
=617
2
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/*implement functions of Dictionary using Hashing ( Division method)*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 10
struct DCT
{
int k;
int val;
}a[MAX];
voidDicHash();
int hash(int);
void insert(int,int,int);
void display();
void size();
void search(int);
void DicHash()
{
int i;
for(i=0;i<MAX;i++)
a[i].k=a[i].val=-1;
}
int hash(int num)
{
int hkey;
hkey=num%10;
return hkey;
}
3
ADVANCED DATASTRUCTURES LAB MANUAL
void display()
{
int i;
printf("Hash Table is\n ");
for(i=0;i<MAX;i++)
printf("%d\t%d\t%d\n",i,a[i].k,a[i].val);
}
void insert(int index,int key,int value)
{
int flag=0,i,count=0;
if(a[index].k==-1)
{
a[index].k=key;
a[index].val=value;
}
else
{
i=0;
while(i<MAX)
{
if(a[i].k != -1)
count++;
i++;
}
if(count==MAX)
{
printf("Hash Table is Full ");
return;
}
for(i=index+1;i<MAX;i++)
4
ADVANCED DATASTRUCTURES LAB MANUAL
if(a[i].k==-1)
{
a[i].k=key;
a[i].val=value;
flag=1;
break;
}
for(i=0;i<index&&flag==0;i++)
if(a[i].k==-1)
{
a[i].k=key;
a[i].val=value;
flag=1;
break;
}
}
}
void size()
{
int i,len=0;
for(i=0;i<MAX;i++)
if(a[i].k != -1)
len++;
printf("size of the Dictionary is len %d",len);
}
void search(int search_key)
{
int i,j;
i=hash(search_key);
if(a[i].k==search_key)
{
5
ADVANCED DATASTRUCTURES LAB MANUAL
6
ADVANCED DATASTRUCTURES LAB MANUAL
do
{
printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter key and value:");
scanf("%d%d",&key,&value);
hkey=hash(key);
insert(hkey,key,value);
break;
case 2:printf("enter key ");
scanf("%d",&key);
search(key);
break;
case 3:display();
break;
case 4:size();
break;
}
}while(ch!=5);
}
7
ADVANCED DATASTRUCTURES LAB MANUAL
EXPECTED OUTPUT:
1.insert
2.search
3.Display
4.size
5.exit
Enter your choice: 1
Enter key and value: 12 13
Enter your choice: 1
Enter key and value: 14 29
Enter your choice: 3
Hash table is:
Index key value
0 -1 -1
1 -1 -1
2 12 13
3 -1 -1
4 14 29
5 -1 -1
6 -1 -1
7 -1 -1
8 -1 -1
9 -1 -1
10 -1 -1
Enter key: 14
8
ADVANCED DATASTRUCTURES LAB MANUAL
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 200
struct DCT
{
int k;
int val;
}a[MAX];
voidDicHash();
int hash(int);
void insert(int,int,int);
void display();
void size();
void search(int);
void DicHash()
{
int i;
for(i=0;i<MAX;i++)
a[i].k=a[i].val=-1;
}
int hash(int key)
{
int hkey;
float A=0.618;
hkey=floor(2*(key*A));
return hkey;
}
void display()
9
ADVANCED DATASTRUCTURES LAB MANUAL
{
int i;
printf("Hash Table is\n ");
for(i=0;i<MAX;i++)
{
if(a[i].k!=-1)
printf("%d\t%d\t%d\n",i,a[i].k,a[i].val);
}
}
void insert(int index,int key,int value)
{
int flag=0,i,count=0;
if(a[index].k==-1)
{
a[index].k=key;
a[index].val=value;
}
else
{
i=0;
while(i<MAX)
{
if(a[i].k != -1)
count++;
i++;
}
if(count==MAX)
{
printf("Hash Table is Full ");
return;
}
for(i=index+1;i<MAX;i++)
10
ADVANCED DATASTRUCTURES LAB MANUAL
if(a[i].k==-1)
{
a[i].k=key;
a[i].val=value;
flag=1;
break;
}
for(i=0;i<index&&flag==0;i++)
if(a[i].k==-1)
{
a[i].k=key;
a[i].val=value;
flag=1;
break;
}
}
}
void size()
{
int i,len=0;
for(i=0;i<MAX;i++)
if(a[i].k != -1)
len++;
printf("size of the Dictionary is len %d",len);
}
void search(int search_key)
{
int i,j;
i=hash(search_key);
if(a[i].k==search_key)
{
11
ADVANCED DATASTRUCTURES LAB MANUAL
12
ADVANCED DATASTRUCTURES LAB MANUAL
do
{
printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter key and value:");
scanf("%d%d",&key,&value);
hkey=hash(key);
insert(hkey,key,value);
break;
case 2:printf("enter key ");
scanf("%d",&key);
search(key);
break;
case 3:display();
break;
case 4:size();
break;
}
}while(ch!=5);
13
ADVANCED DATASTRUCTURES LAB MANUAL
EXPECTED OUTPUT:
1.Insert
2.search
3.display
4.size
5.exit
Hash table is
14 12 359
28 23 456
Enter key: 12
14
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE2:
AIM: To perform various operations i.e, insertions and deletions on AVL tree
DESCRIPTION: AVL tree is a self-balancing Binary Search Tree (BST) where the difference
between heights of left and right subtrees cannot be more than one for all nodes.
INSERTION:
To make sure that the given tree remains AVL after every insertion, we must augment the
standard BST insert operation to perform some re-balancing. Following are two basic
operations that can be performed to re-balance a BST without violating the BST property
(keys(left)<key(root)<keys(right)).
1)LeftRotation
2)Right Rotation
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ \ Right Rotation / \
x T3 – - – - – - – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
Keys in both of the above trees follow the following order
keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.
15
ADVANCED DATASTRUCTURES LAB MANUAL
z z x
/ \ / \ / \
y T4 Left Rotate (y) x T4 Right Rotate(z) y z
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
z y
/ \ / \
T1 y Left Rotate(z) z x
/ \ - - - - - - - -> / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
z z x
/ \ / \ / \
T1 y Right Rotate (y) T1 x Left Rotate(z) z x
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
x T4 T2 y T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
DELETION:
To make sure that the given tree remains AVL after every deletion, we must augment the
standard BST delete operation to perform some re-balancing. Following are two basic
operations that can be performed to re-balance a BST without violating the BST property
(keys(left)<key(root)<keys(right)).
1)LeftRotation
2) Right Rotation
16
ADVANCED DATASTRUCTURES LAB MANUAL
17
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
5.exit\n");
18
ADVANCED DATASTRUCTURES LAB MANUAL
printf("Enter ur choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter item to be inserted in the avl tree:");
scanf("%d",&item);
avl=avlinsert(avl,item,&h);
break;
case 2:printf("Enter item to be deleted from the avl tree:");
scanf("%d",&item);
avl=avldelete(avl,item,&h);
break;
case 3:avl=deltree(avl);
case 4:display(avl);
break;
}
}while(ch!=5);
}
/* Inserts an element intp tree */
struct AVLNode * avlinsert(struct AVLNode *root,int data,int *h)
{
struct AVLNode *node1,*node2;
if(!root)
{
root=(struct AVLNode *)malloc(sizeof(struct AVLNode));
root->data=data;
root->left=NULL;
root->right=NULL;
root->balfact=0;
*h=TRUE;
return(root);
19
ADVANCED DATASTRUCTURES LAB MANUAL
}
if(data < root->data)
{
root->left=avlinsert(root->left,data,h);
root->balfact=-1;
20
ADVANCED DATASTRUCTURES LAB MANUAL
else
root->balfact=0;
if(node2->balfact==-1)
node1->balfact=1;
else
node1->balfact=0;
root=node2;
}
root->balfact=0;
*h=FALSE;
break;
case 0:
root->balfact=1;
break;
case -1:
root->balfact=0;
*h=FALSE;
}
}
}
if(data > root->data)
{
root->right=avlinsert(root->right,data,h);
/* If the right subtree is higher */
if(*h)
{
switch(root->balfact)
{
case 1:
root->balfact=0;
*h=FALSE;
21
ADVANCED DATASTRUCTURES LAB MANUAL
break;
case 0:
root->balfact=-1;
break;
case -1:
node1=root->right;
if(node1->balfact==-1)
{
printf("\n Left rotation along %d. ",root->data);
root->right=node1->left;
node1->left=root;
root->balfact=0;
root=node1;
}
else
{
printf("\n Double 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
22
ADVANCED DATASTRUCTURES LAB MANUAL
node1->balfact=0;
root=node2;
}
root->balfact=0;
*h=FALSE;
}
}
}
return(root);
}
/* Deletes an item from the tree */
struct AVLNode * avldelete(struct AVLNode *root,int data,int *h)
{
struct AVLNode *node,*tp;
node=root;/*if there is only one node*/
if((root)&&(node->left==NULL)&&(node->right==NULL))
{
*h=TRUE;
free(node);
root=NULL;
return (root);
}
if(!root)
{
printf("\n No such data. ");
return (root);
}
else
{
23
ADVANCED DATASTRUCTURES LAB MANUAL
{
root->left=avldelete(root->left,data,h);
if(*h)
root=balr(root,h);
}
else
{
if(data > root->data)
{
root->right=avldelete(root->right,data,h);
if(*h)
root=ball(root,h);
}
else
{
node=root;
if((node->right==NULL)&&(node->data==data))
{
tp=node;
root=node->left;
printf("new:%d",root->data);
getch();
tp->left=NULL;
free(tp);
*h=TRUE;
return(root);
}
else
{
if(node->left==NULL)
24
ADVANCED DATASTRUCTURES LAB MANUAL
root=node->right;
*h=TRUE;
free(node);
}
else
{
node->right=del(node->right,node,h);
if(*h)
root=ball(root,h);
}
}
}
}
}
return(root); }
struct AVLNode * del(struct AVLNode *succ,struct AVLNode *node,int *h)
{
struct AVLNode *temp=succ;
if(succ->left!=NULL)
{
succ->left=del(succ->left,node,h);
if(*h)
succ=balr(succ,h);
}
else
{
temp=succ;
node->data=succ->data;
succ=succ->right;
free(temp);
*h=TRUE;
25
ADVANCED DATASTRUCTURES LAB MANUAL
}
return(succ);
}
/* Balance the tree , if right subtree is higher */
struct AVLNode * balr(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("\n Left 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
26
ADVANCED DATASTRUCTURES LAB MANUAL
{
root->balfact=node1->balfact=0;
}
root=node1;
}
else
{
printf("\n Double 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;
node2->balfact=0;
}
}
return (root);
}
27
ADVANCED DATASTRUCTURES LAB MANUAL
struct AVLNode * ball(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->left;
if(node1->balfact >= 0)
{
printf("]n Right 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;
28
ADVANCED DATASTRUCTURES LAB MANUAL
}
else
{
printf("\n Double rotation , left along %d ",node1->data);
node2=node1->right;
node1->right=node2->left;
node2->left=node1;
printf(" then right along %d .\n",root->data);
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;
node2->balfact=0;
}
}
return (root);
}
/*n Displays the tree in-order */
void display(struct AVLNode *root)
{
if(root!=NULL)
{
display(root->left);
printf("%d\t",root->data);
29
ADVANCED DATASTRUCTURES LAB MANUAL
display(root->right);
}
}
/* Deletes the tree */
struct AVLNode *deltree(struct AVLNode * root)
{
int h;
root->left=NULL;
root->right=NULL;
free(root);
root=NULL;
return(root);
}
EXPECTED OUTPUT:
30
ADVANCED DATASTRUCTURES LAB MANUAL
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:23
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:12
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:4
12 23 45
1.INSERT…
2.DELETE AN ITEM…
31
ADVANCED DATASTRUCTURES LAB MANUAL
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:18
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:22
Left Rotation along 12
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:4
12 18 22 23 45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:17
Right Rotation along 23
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
32
ADVANCED DATASTRUCTURES LAB MANUAL
5.EXIT
ENTER UR CHOICE:4
12 17 18 22 23 45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:2
Enter element to be deleted:17
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:4
12 18 22 23 45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:1
Enter an element to be inserted in the AVL Tree:40
Left Rotation along 18
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:4
33
ADVANCED DATASTRUCTURES LAB MANUAL
12 18 22 23 40 45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:2
Enter Element to be deleted from the AVL Tree:23
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:2
Enter Element to be deleted from the AVL Tree:18
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:2
Enter Element to be deleted from the AVL Tree:40
Right Rotation along 45
1.INSERT…
2.DELETE AN ITEM…
3.DELETION OF AN AVL TREE
4.DISPLAY
5.EXIT
ENTER UR CHOICE:4 12 22 45
EXERCISE:4
AIM:To implement operations on Binary heap
34
ADVANCED DATASTRUCTURES LAB MANUAL
DESCRIPTION:
Binary Heap: A binary heap is defined as a complete binary tree with elements at every
node being either less than or equal to the element at its left and the right child.
MAX HEAP:The elements at every node will either be less than or equal to the element at its
left and right child
MIN HEAP:The elements at every node will either be greater than or equal to the element
at its left and right child.
There are two types of operations that are performed in Binary heap
Insertion in a binary heap
Deleting an element from a binary heap
INSERT AN ELEMENT:In binary heap elements can be added randomly.
ALGORITHM FOR INSERTION:
Step1:Add the new value and set its pos SET N=N+1,POS=N
Step2:SET HEAP[N]=VAL;
Step3:Find appropriate location of VAL .Repeat steps 4,5 while POS<0
Step4:SET PAR=POS/2;
Step5:if HEAP[POS]<=HEAP[PAR],then goto step6
Else swap HEAP[POS],HEAP[PAR]
POS=PAR
Step6:return
DELETE AN ELEMENT:In binary heap only the element with the higest value is removed in
case of MAX HEAP,and the element with the minimum value is removed in case of MINHEAP
ALGORITHM FOR DELETION:
Step1: [Remove the last node from the heap]
SET LAST=HEAP[N],SET N=N-1
Step2: [Initialize]SET PTR=0,LEFT=1,RIGHT=2
Step3: SET HEAP[PTR]=LAST
35
ADVANCED DATASTRUCTURES LAB MANUAL
Step6: if HEAP[RIGHT]<=HEAP[LEFT] then Swap HEAP[PTR],HEAP[LEFT]
SET PTR=LEFT
Else
Swap HEAP[PTR],HEAP[RIGHT]
SET PTR=RIGHT
Step7: SET LEFT=2*PTR & RIGHT=LEFT+1
Step8: return
SAMPLE PROGRAM:
/* Program to implement Binary heap operations */
36
ADVANCED DATASTRUCTURES LAB MANUAL
#include<stdio.h>
#include<conio.h>
struct heap
{
int h[50];
int hsize;
}he;
void create();
void insert();
int delete();
void size();
void display();
void size()
{
he.hsize=0;
}
void create()
{
Int i,root,ch;
int p;
printf("\n Enter Heap size: \n");
scanf("%d",&he.hsize);
printf("\n Enter Elements of Heap : \n");
for(i=1;i<=he.hsize;i++)
{
scanf("%d",&he.h[i]);
}
for(root=he.hsize/2;root>=1;root--)
{
p=he.h[root];
ch=root*2;
37
ADVANCED DATASTRUCTURES LAB MANUAL
while(ch<=he.hsize)
{
if(ch<he.hsize&&he.h[ch+1]>he.h[ch])
ch++;
if(p>he.h[ch])
break;
he.h[ch/2]=he.h[ch];
ch=ch*2;
}
he.h[ch/2]=p;
}
}
void display()
{
int i;
if(he.hsize==0)
printf("heap empty\n");
else
{
printf("\n\n HEAP ELEMENTS \n\n");
for(i=1;i<=he.hsize;i++)
printf("%d\t",he.h[i]);
}
}
void insert()
{
int el;
int cn;
printf("\n Enter Element: \n");
scanf("%d",&el);
he.hsize++;
38
ADVANCED DATASTRUCTURES LAB MANUAL
cn=he.hsize;
while(cn!=1 && he.h[cn/2]<el)
{
he.h[cn]=he.h[cn/2];
cn=cn/2;
}
he.h[cn]=el;
}
int delete()
{
int i,ch,el,le;
if(he.hsize==0)
{
printf("\n heap empty. \n");
return(0);
}
else
{
el=he.h[1];
le=he.h[he.hsize];
he.hsize--;
ch=2;
while(ch<=he.hsize)
{
if(ch<he.hsize &&he.h[ch+1]>he.h[ch])
ch++;
if(le>he.h[ch])
break;
he.h[ch/2]=he.h[ch];
ch=ch*2;
}
39
ADVANCED DATASTRUCTURES LAB MANUAL
he.h[ch/2]=le;
return(el);
}
}
void main()
{
int x,opt,i;
size();
do
{
printf(”\n BINARY HEAP OPERATIONS”);
printf("\n1.Create \n2.Insert \n3.DELETE \n4.Display \n5.Exit");
printf("\n Enter Option \n");
scanf("%d",&opt);
switch(opt)
{
case 1: create();
break;
case 2: insert();
break;
case 3: x=delete();
if(x!=0)
printf("\n Deleted Element : \t %d",x);
break;
case 4:display();
break;
case 5:break; }
}while(opt!=5);
getch(); }
EXPECTED OUTPUT:
BINARY HEAP OPERATIONS
40
ADVANCED DATASTRUCTURES LAB MANUAL
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:1
Enter Heap Size:5
Enter Elements of Heap:12 45 23 86 56
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:4
Heap Elements: 86 56 23 12 45
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:2
Enter Element: 28
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:4
41
ADVANCED DATASTRUCTURES LAB MANUAL
Heap Elements: 86 56 28 12 45 23
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:3
Deleted Element:86
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:4
Heap Elements : 56 45 28 12 23
BINARY HEAP OPERATIONS
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter option:5
EXERCISE-5:
AIM: To implement operations on graphs
42
ADVANCED DATASTRUCTURES LAB MANUAL
DESCRIPTION:
GRAPH: A graph is a collection of nodes called vertices and a collection of segments called
lines,connecting parts of vertices Graphs may be Directed or Un-Directed.
OPERATIONS ON GRAPHS:
There are several primitive graph operations that provide the basic modules needed
to maintain a graph.
1. Insert a vertex.
2. Delete a vertex
3. Find a vertex.
4. Insert an edge.
5. Delete an edge.
6. Find edge.
1.INSERT A VERTEX:- Insert vertex adds a new vertex to a graph.When a vertex is inserted,it
is disjoint,That is,it is not connected to any other vertices is just the first step in the insertion
process. After a vertex is inserted,it must be connected.
Algorithm for Insert Vertex: It allocates memory for a new vertex and copies the` data to it.
Input:Graph is a reference to graph head structure datain contains data to be inserted into
vertex.
Output: New vertex allocated and data copied.
Algorithm insertvertex(graph,datain) :
Step1: Allocate memory for new vertex.
Step2: Store datain in new vertex.
Step3: Initialize metadata elements in newnode.
Step4: Increment graph count.
Step5: if(graph is empty)
5.1 Set graph first to newnode.
STEP : 6 else
6.1 Search for insertion point
6.2 If(inserting before first vertex
43
ADVANCED DATASTRUCTURES LAB MANUAL
end insert vetex.
2.DELETE VERTEX: Delete vertex removes a vertex from the graph when a vertex is
deleted,all connecting edges are also removed.The first thing we have to do to delete a
vertex is find it. Once we have found it, however we also need to make sure that it is
disjoint,that is we need to ensure that there are no arcs leaving (or) entering the vertex.
Algorithm for Delete Vertex:- It deletes an existing vertex only if its degree os “0”.
Input: Graph is a reference pointer to graph head key is the key of the vertex to be deleted.
Output: Vertex deleted(if degree zero)
Return:
+1 if successful
-1 if degree not zero
-2 if key not found
Algorithm delete vertex(graph,key)
STEP : 1 if(empty graph)
1.1 return -2
STEP : 2 Search for vertex to be deleted.
STEP : 3 If vertex not found
3.1 return -2
STEP : 4 Test degree of the vertex
If(vertex indegree>0 OR outdegree>0)
4.1 return -1
STEP : 5 Delete vertex
STEP : 6 Decrement graph count
STEP : 7 return 1
End delete vertex.
3.FIND VERTEX:-Find vertex traverses a graph, looking for a special vertex. If the vertex is
found its data are returned. If it is not found, an error is indicated.
44
ADVANCED DATASTRUCTURES LAB MANUAL
Dataout is reference to data variable.
Output Vertex data copied to dataout.
Return:
+1 isf successful
-2 if key not found
Algorithm retrieve vertex(graph,key,dataout)
STEP : 1 If graph is empty return -2
STEP : 2 Search for vertex
STEP : 3 if vertex found
3.1 move location pointer data to dataout
Return 1
STEP : 4 otherwise return -2
End find vertex.
4.INSERT EDGE:- Add edge connects a vertex to a destination vertex. Two vertices must be
specified, to add an edge. If the graph is a digraph, one of the vertices must be specified as
the source and the other one as the destination. If a vertex tequires multiple edges, add an
edge must be called once for each adjacent vertex.Insert arc (or) edge requires two points in
the graph. The source vertex (fromptr) and the destination vertex(toptr).Each vertex is
identified by its key value rather than by its physical address.
Algorithm insertArc(graph,fromkey,tokey)
45
ADVANCED DATASTRUCTURES LAB MANUAL
STEP : 1 Allocate memory for new arc
STEP : 2 Search and set fromvertex.
STEP : 3 if(from vertex not found)
Return -2
STEP : 4 Search and set tovertex
STEP : 5 if(tovetex not found)
Return -3
STEP : 6 From and to vertices located, Insert new arc
STEP : 7 Increment fromvertex outdegree
STEP : 8 Increment tovertex indegreee
STEP : 9 Set arc destination to tovertex
STEP : 10 if(fromvertex arc list empty)
10.1 Set fromvertex first arc to new arc
10.2 Set new arc next arc to null
10.3 return 1
STEP : 11 Find insertion point in the arc list.
STEP : 12 if(insert at beginning of arc list)
12.1 Insertion before first arc i.e set fromvertex
First arc to new arc
STEP : 13 Insert in arc list
STEP : 14 return 1
End insertArc
4.DELETE EDGE: Delete edge removes one edge from a graph.to identify an arc, we need
two vertices. The vertices are identified by their key. The algorithm therefore first searches
the vertex list for the start vertex and searches the vertex list for the start vertex and
searches its adjacency list for the destination vertex. After locating and deleting arc, the
dergree in the form and to vertices is adjusted and the memory recycled.
46
ADVANCED DATASTRUCTURES LAB MANUAL
Input:Graph is reference to a graph head structure fromkey is the key of the source vertex
tokey is the key of destination vertex
Output: Vertex deleted.
Return:
+1 if successful
-2 if fromkey not found
-3 if tokey not found
STEP 1 : if(empty graph)
Return -2
STEP : 2 Search and set fromvertex to vertex with key equal to fromkey.
STEP : 3 if(fromvertex not found)
Return -2
STEP : 4 if(fromvertex arc list null) then
Return -3
STEP : 5 Search and find arc with key equql to tokey
STEP : 6 if(tokey not found) then
Return -3
STEP : 7 7.1 Set tovertex to arc destination
7.2 delete arc
7.3 decrement fromvertex outdegree
7.4 decrement tovertex indegree
7.5 return
End deleteArc
SAMPLE PROGRAM:
47
ADVANCED DATASTRUCTURES LAB MANUAL
#include<stdio.h>
struct node
{
struct node *next;
char name;
struct edge *adj;
}*start = NULL;
struct edge
{
char dest;
struct edge *link;
};
struct node *find( char item );
main()
{
int choice;
char node, origin, destin;
while ( 1 )
{
printf(“\n GRAPH OPERATIONS \t ”);
printf( "1.Insert a node\n" );
printf( "2.Insert an edge\n" );
printf( "3.Delete a node\n" );
printf( "4.Delete an edge\n" );
printf( "5.Display\n" );
printf( "6.Exit\n" );
printf( "Enter your choice : " );
scanf( "%d", &choice );
48
ADVANCED DATASTRUCTURES LAB MANUAL
switch ( choice )
{
case 1:printf( "Enter a node to be inserted : " );
fflush( stdin );
scanf( "%c", &node );
insert_node( node );
break;
case 2: printf( "Enter an edge to be inserted : " );
fflush( stdin );
scanf( "%c %c", &origin, &destin );
insert_edge( origin, destin );
break;
case 3:printf( "Enter a node to be deleted : " );
fflush( stdin );
scanf( "%c", &node );
/*This fn deletes the node from header node list*/
delete_node( node );
/* This fn deletes all edges coming to this node */
delnode_edge( node );
break;
case 4:printf( "Enter an edge to be deleted : " );
fflush( stdin );
scanf( "%c %c", &origin, &destin );
del_edge( origin, destin );
break;
case 5:display();
break;
case 6:exit();
default:printf( "Wrong choice\n" );
break;
49
ADVANCED DATASTRUCTURES LAB MANUAL
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert_node( char node_name )
{
struct node * tmp, *ptr;
tmp = malloc( sizeof( struct node ) );
tmp->name = node_name;
tmp->next = NULL;
tmp->adj = NULL;
if ( start == NULL )
{
start = tmp;
return ;
}
ptr = start;
while ( ptr->next != NULL )
ptr = ptr->next;
ptr->next = tmp;
} /*End of insert_node()*/
delete_node( char u )
{
struct node * tmp, *q;
if ( start->name == u )
{
tmp = start;
start = start->next; /* first element deleted */
free( tmp );
return ;
}
50
ADVANCED DATASTRUCTURES LAB MANUAL
q = start;
while ( q->next->next != NULL )
{
if ( q->next->name == u ) /* element deleted in between */
{
tmp = q->next;
q->next = tmp->next;
free( tmp );
return ;
}
q = q->next;
} /*End of while*/
if ( q->next->name == u ) /* last element deleted */
{
tmp = q->next;
free( tmp );
q->next = NULL;
}
} /*End of delete_node()*/
delnode_edge( char u )
{
struct node * ptr;
struct edge *q, *start_edge, *tmp;
ptr = start;
while ( ptr != NULL )
{
/* ptr->adj points to first node of edge linked list */
if ( ptr->adj->dest == u )
{
tmp = ptr->adj;
51
ADVANCED DATASTRUCTURES LAB MANUAL
ptr->adj = ptr->adj->link; /* first element deleted */
free( tmp );
continue; /* continue searching in another edge lists */
}
q = ptr->adj;
while ( q->link->link != NULL )
{
if ( q->link->dest == u )/* element deleted in between */
{
tmp = q->link;
q->link = tmp->link;
free( tmp );
continue;
}
q = q->link;
} /*End of while*/
if ( q->link->dest == u ) /* last element deleted */
{
tmp = q->link;
free( tmp );
q->link = NULL;}
ptr = ptr->next;
} /*End of while*/
} /*End of delnode_edge()*/
insert_edge( char u, char v )
{
struct node * locu, *locv;
struct edge *ptr, *tmp;
locu = find( u );
locv = find( v );
52
ADVANCED DATASTRUCTURES LAB MANUAL
if ( locu == NULL )
{
printf( "Source node not present ,first insert node %c\n", u );
return ;
}
if ( locv == NULL )
{
printf( "Destination node not present ,first insert node %c\n", v );
return ;
}
tmp = malloc( sizeof( struct edge ) );
tmp->dest = v;
tmp->link = NULL;
if ( locu->adj == NULL ) /* item added at the begining */
{
locu->adj = tmp;
return ;
}
ptr = locu->adj;
while ( ptr->link != NULL )
ptr = ptr->link;
ptr->link = tmp;
} /*End of insert_edge()*/
struct node *find( char item )
{
struct node *ptr, *loc;
ptr = start;
while ( ptr != NULL )
{
if ( item == ptr->name )
{
53
ADVANCED DATASTRUCTURES LAB MANUAL
loc = ptr;
return loc;
}
else
ptr = ptr->next;
}
loc = NULL;
return loc;
} /*End of find()*/
del_edge( char u, char v )
{
struct node * locu, *locv;
struct edge *ptr, *tmp, *q;
locu = find( u );
if ( locu == NULL )
{
printf( "Source node not present\n" );
return ;
}
if ( locu->adj->dest == v )
{
tmp = locu->adj;
locu->adj = locu->adj->link; /* first element deleted */
free( tmp );
return ;
}
q = locu->adj;
while ( q->link->link != NULL )
{
if ( q->link->dest == v ) /* element deleted in between */
54
ADVANCED DATASTRUCTURES LAB MANUAL
{
tmp = q->link;
q->link = tmp->link;
free( tmp );
return ;
}
q = q->link;
} /*End of while*/
if ( q->link->dest == v ) /* last element deleted */
{
tmp = q->link;
free( tmp );
q->link = NULL;
return ;
}
printf( "This edge not present in the graph\n" );
} /*End of del_edge()*/
display()
{
struct node * ptr;
struct edge *q;
ptr = start;
while ( ptr != NULL )
{
printf( "%c ->", ptr->name );
q = ptr->adj;
while ( q != NULL )
{
printf( " %c", q->dest );
q = q->link;
55
ADVANCED DATASTRUCTURES LAB MANUAL
}
printf( "\n" );
ptr = ptr->next;
}
} /*End of display()*/
SAMPLE OUTPUT:
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :1
Enter a node to be inserted:1
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :1
Enter a node to be inserted:2
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :1
Enter a node to be inserted:3
56
ADVANCED DATASTRUCTURES LAB MANUAL
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :5
1 ->
2 ->
3 ->
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :2
Enter an edge to be inserted:1 2
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :2
Enter a edge to be inserted:2 3
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
57
ADVANCED DATASTRUCTURES LAB MANUAL
5.Exit
Enter your choice :2
Enter a fdge to be inserted:3 1
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :5
1 ->2
2 ->3
3 ->1
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :3
Enter a node to be deleted:3
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :5
1 ->2
2->
58
ADVANCED DATASTRUCTURES LAB MANUAL
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :4
Enter an edge to be deleted:1 2
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :5
1 ->
2 ->
GRAPH OPERATIONS
1.Insert a node
2.Insert an edge
3.Delete an edge
4.Display
5.Exit
Enter your choice :6
59
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE:6
AIM:To implement Depth First Search for a graph nonrecursively.
DESCRIPTION:
Graph: A graph is a collection of nodes called vertices, and a collection of segments called
lines, connecting parts of vertices.
Graph Traversals: Traversal means visiting each node at least once in a graph. There are
multiple paths to a vertex we may arrive at it from more than one direction as we traverse
the graph.
The traditional solution to this problem is to introduce a visited flag at each vertex.
Before the traversal we can set the visited flag in each vertex to off. Then, as we set
the visited flag to on to indicate that the data have been processed.
Depth First Search:
“STACK” data structure is suitable to achieve data first structure. “Stack” is a lost in first out
structure.
Stack data structure is used to traverse the graph in DFS manner.
As the algorithm proceeds, nodes status will be changed.
Initially, we assume all the nodes will be in un-processed state.
When they are in stack, we assume they are in the ready state.
When they leave the stack, we consider them that they are processed.
DFS ALGORITHM:
Step 1: Initialization
a) Initialize stack to empty.
b) Mark all nodes as not visited.Push node 0 onto the stack and
mark it as visited.
Step 2: While (stack is not empty)
{
a) Pop value from stack.
b) Push all nodes adjacent to popped node and which have not
been visited as yet onto the stack.
c) Mark all pushed nodes as visited.
}
60
ADVANCED DATASTRUCTURES LAB MANUAL
/*To implement Depth first search of a graph non-recursively*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int adj[5][5]={{0,1,1,1,0},
{1,0,1,0,1},
{1,1,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}};
int visited[30];
struct stack
{
int s[30];
int sp;
};
typedef struct stack stk;
stk st;
void push(int val);
int pop();
int isempty();
void disp();
void main()
{
int i,j,val;
int dfs[30];
st.sp=-1;
clrscr();
for(i=0;i<5;i++)
{
printf(“\n”);
61
ADVANCED DATASTRUCTURES LAB MANUAL
for(j=0;j<5;j++)
printf(“%d\t”,adj[i][j]);
}
i=0;
push(i);
visited[i]=1;
disp();
while(isempty()==0)
{
val=pop();
dfs[i]=val;
for(j=0;j<5;j++)
{
if(adj[val][j]==1)
{
if(visited[j]==0)
{
push(j);
visited[j]=1;
}
}
}
disp();
i=i+1;
}
printf(“\nDfs for the graph”);
for(i=0;i<5;i++)
printf(“%d\t”,dfs[i]);
getch();
}
62
ADVANCED DATASTRUCTURES LAB MANUAL
int isempty()
{
if(st.sp==-1)
{
return1;
}
else
return0;
}
void push(int val)
{
st.sp++;
st.s[st.sp]=val;
}
int pop()
{
int val,ans;
ans=isempty();
if(ans==0)
{
val=st.s[st.sp];
st.sp--;
}
else
printf(“\n stack is empty “);
return(val);
}
void disp()
{
int i;
63
ADVANCED DATASTRUCTURES LAB MANUAL
printf(“\n”);
if(isempty()==0)
{
printf(“\n Elements of stack”);
for(i=st.sp;i>=0;i--)
printf(“\n%d\t”,st.s[i]);
}
}
EXPECTED OUTPUT:
0 1 1 1 0
1 0 1 0 1
1 1 0 1 0
1 0 1 0 1
0 1 0 1 0
Elements of stack
0
Elements of stack
3
2
1
Elements of stack
4
2
1
Elements of stack
2
1
Elements of stack
1
Dfs for the graph
0 3 4 2 1
64
ADVANCED DATASTRUCTURES LAB MANUAL
Exercise7:
AIM: Program for Breadth First Search algorithm
DESCRIPTION:
Graph:
A graph is a collection of nodes called vertices and collection ofsegments called lines
connecting parts of vertices.
Graph Traversals:
Traversals means visiting each node atleast once in a graph.There are multiple paths to
a vertex.We may arrive at it from more than one direction as we traverse the graph.
The traditional solution to this problem is to include a visited flag at each vertex.
Before the traversal we set the visited flag in each vertex to off.Then,as we traverse
the graph,we set the visited flag to on to indicate that the data have been processed.
Breadth First search:
Data structure “Queue” is used for “BFS”.
“Queue” is a First In First Out (FIFO) structure.
Queue Data structure is used to traverse the graph in BFS manner.
As the algorithm proceeds,nodes status will be changed.
Initially,we assume all the nodes will be in un-processed state.
When they are in Queue,we assume they are in ready state.
When they leave the Queue,we consider them that they are processed.
BFS ALGORITHM:
Step 1: Initialization
a) Initialize Queue to empty.
b) Mark all nodes as not visited.
c) Insert node “0” and mark it as visited.
Step 2: while(Queue is not empty)
{
Delete element from Queue.
d) Insert nodes adjacent to deleted node and which have not been visited.
e) Mark all inserted nodes as visited. }
65
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/*program for Breadth first search */
#include<stdio.h>
#include<conio.h>
int adj[30][30];
int visited[30];
struct queue
{
int data[30];
int front,rear;
};
typedef struct queue que;
que q;
void insert(int val);
int delete();
int isempty();
void disp();
void main()
{
int nodes;
int i,j,val;
int bfs[30];
q.rear=-1;
q.front=0;
clrscr();
printf(“\n enter number of nodes in the graph”);
scanf(“%d”,&nodes);
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
66
ADVANCED DATASTRUCTURES LAB MANUAL
{
printf(“n enter edges[%d][%d]”,i,j);
scanf(“%d”,&adj[i][j]);
}
}
for(i=0;i<nodes;i++)
{
printf(“\n”);
for(j=0;j<nodes;j++)
printf(“%d\t”,adj[i][j]);
}
i=0;
insert(i);
visited[i]=1;
disp();
while(isempty()==0)
{
val=delete();
bfs[i]=val;
for(j=0;j<nodes;j++)
{
if(adj[val][j]==1)
{
if(visited[j]==0)
{
insert(j);
visited[j]=1;
}
}
}
67
ADVANCED DATASTRUCTURES LAB MANUAL
disp() ;
i=i+1;
}
printf(“\n BFS for the graph \n”);
for(i=0;i<nodes;i++)
printf(“%d\t”,BFS[i]);
getch();
}
void insert(int val)
{
q.rear++;
q.data[q.rear]=val;
}
int delete()
{
int k,ans;
k=isempty();
if(k==0)
{
ans=q.data[q.front];
q.front++;
}
else
{
printf(“Queue is empty”);
ans=-1;
}
return(ans);
}
68
ADVANCED DATASTRUCTURES LAB MANUAL
int isempty()
{
int ans;
if(q.rear<q.front)
ans=1;
else
ans=0;
return(ans);
}
void disp()
{
int ans,I;
printf(“data elements in Queue:\n”);
ans=isempty();
if(ans==0)
{
for(i=q.front;i<=q.rear;i++)
printf(“%d\n”,q.data[i]);
}
else
printf(“Queue is empty \n”);
}
69
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE OUTPUT :
Enter no.of nodes in the graph: 4
Enter edges[0][0]: 0
Enter edges[0][1]: 1
Enter edges[0][2]: 1
Enter edges[0][3]: 1
Enter edges[1][0]: 0
Enter edges[1][1]: 0
Enter edges[1][2]: 0
Enter edges[1][3]: 1
Enter edges[2][0]: 0
Enter edges[2][1]: 0
Enter edges[2][2]: 0
Enter edges[2][3]: 1
Enter edges[3][0]: 0
Enter edges[3][1]: 0
Enter edges[3][2]: 0
Enter edges[3][3]: 0
0 1 1 1
0 0 0 1
0 0 0 1
0 0 0 0
Data elements in the Queue
0
Data elements in the Queue
3
2
1
Data elements in the Queue
2
1
Data elements in the Queue
1
Data elements in the Queue
Queue is empty
Bfs for the graph 0 3 2 1
70
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE-8:
71
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/* program to find minimum spanning tree using KRUSKAL’S Algorithm */
#include<stdio.h>
#define INF 1000
char vertex[10];
int wght[10][10];
int span_wght[10][10];
int source
struct Sort
{
int v1,v2;
int weight;
}que[20];
int n,ed,f,r;
int cycle(int s,int d)
{
int j,k;
if(source==d)
return 1;
for(j=0;j<n;j++)
if(span_wght[d][j]!=INF && s!=j)
{
if(cycle(d,j))
return 1;
}
return 0;
}
void build_tree()
{
int i,j,w,k,count=0;
72
ADVANCED DATASTRUCTURES LAB MANUAL
for(count=0;count<n;f++)
{
i=que[f].v1;
j=que[f].v2;
w=que[f].weight;
span_wght[i][j]=span_wght[j][i]=w;
source=i;
k=cycle(i,j);
if(k)
span_wght[i][j]=span_wght[j][i]=INF;
else
count++;
}
}
void swap(int *i,int *j)
{
int t;
t=*i;
*i=*j;
*j=t;
}
void main()
{
int i,j,k=0,temp;
int sum=0;
clrscr();
printf("\n\n\tKRUSKAL'S ALGORITHM TO FIND SPANNING TREE\n\n");
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&n);
73
ADVANCED DATASTRUCTURES LAB MANUAL
for(i=0;i<n;i++)
{
printf("\n\tEnter %d value : ",i+1);
fflush(stdin);
scanf("%c",&vertex[i]);
for(j=0;j<n;j++)
{
wght[i][j]=INF;
span_wght[i][j]=INF;
}
}
printf("\n\nGetting Weight\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
printf("\nEnter 0 if path Doesn't exist between %c to %c : ",vertex[i],vertex[j]);
scanf("%d",&ed);
if(ed>=1)
{
wght[i][j]=wght[j][i]=ed;
que[r].v1=i;
que[r].v2=j;
que[r].weight=wght[i][j];
if(r)
{
for(k=0;k<r;k++)
if(que[k].weight>que[r].weight)
{
swap(&que[k].weight,&que[r].weight);
swap(&que[k].v1,&que[r].v1);
74
ADVANCED DATASTRUCTURES LAB MANUAL
swap(&que[k].v2,&que[r].v2);
}
}
r++;
}
}
clrscr();
printf("\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n");
printf("\n\tweight matrix\n\n\t");
for(i=0;i<n;i++,printf("\n\t"))
for(j=0;j<n;j++,printf("\t"))
printf("%d",wght[i][j]);
build_tree();
printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");
printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(span_wght[i][j]!=INF)
{
printf("\n\t\t%c ------ %c = %d ",vertex[i],vertex[j],span_wght[i][j]);
sum+=span_wght[i][j];
}
printf("\n\n\t\tTotal Weight : %d ",sum);
getch();
}
75
ADVANCED DATASTRUCTURES LAB MANUAL
EXPECTED OUTPUT:
Getting Weight:
Weight matrix
1000 2 4 3 1000
2 1000 1000 2 1
4 1000 1000 1 1000
3 2 1 1000 4
1000 1 1000 4 1000
LIST OF EDGES
1------2=2
2------4=2
2------5=1
3------4=1
Total Weight:6
76
ADVANCED DATASTRUCTURES LAB MANUAL
Exercise 9:
AIM: To implement Prim’s algorithm to generate a min-cost spanning tree.
DESCRIPTION:
Spanning tree: Let G be a graph containing n verticies.Then a tree which is derived from Gis
called spanning tree if and only if the number of verticies in G should like in the derived tree
Minimal Spanning Tree:A spanning tree whose total weight is least among the group of
spanning trees is said to be “Minimal Spanning Tree”.
PRIM’S Algoritham:PRIM’S algorithm builds a minimum spanning tree by deleting the edges
sequentially that does not effect the graph.i.e that does not disconnect the graph until n-1
edges remain.
Algorithm:
Step1:Let G ={V,E} be a graph
Step2:MST={}//MST is the set of all edges that make up minimal spanning tree
Step3:Select the starting node
While(MST has <n-1 edges) && (Eis not empty)
{
3.1.Select a node from adjacent nodes to the node selected such that its
Weight is minimal.
3.2. If deletion of that edge does not disconnect the graph then delete edge
(u,v) from E.Otherwise add it to MST
}
77
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/* program to implement prim’s algorithm*/
#include<stdio.h>
#define INF 1000
int vertex[10];
int wght[10][10];
int new_wght[10][10];
int closed[10];
int n;
int inclose(int i,int n1)
{
/*chk for the ith vertex presence in closed*/
int j;
for(j=0;j<=n1;j++)
if(closed[j]==i)
return 1;
return 0;
}
void buildtree()
{
int i=0,j,count=0;
int min,k,v1=0,v2=0;
closed[0]=0;
while(count<n-1)
{
min=INF;
for(i=0;i<=count;i++)
for(j=0;j<n;j++)
if(wght[closed[i]][j]<min && !inclose(j,count))
78
ADVANCED DATASTRUCTURES LAB MANUAL
{
min=wght[closed[i]][j];
v1=closed[i];
v2=j;
}
new_wght[v1][v2]=new_wght[v2][v1]=min;
count++;
closed[count]=v2;
printf("\nScan : %d %d---------%d wght = %d \n",count,v1+1,v2+1,min);
getch();
}
}
void main()
{
int i,j,ed,sum=0;
clrscr();
printf("\n\n\tPRIM'S ALGORITHM TO FIND SPANNING TREE\n\n");
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
vertex[i]=i+1;
for(j=0;j<n;j++)
{
wght[i][j]=INF;
new_wght[i][j]=INF;
}
}
printf("\n\nGetting Weight.\n");
79
ADVANCED DATASTRUCTURES LAB MANUAL
printf("\n\tEnter 0 if path doesn't exist between {v1,v2} else enter the wght\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
printf("\n\t%d -------- %d : ",vertex[i],vertex[j]);
scanf("%d",&ed);
if(ed>=1)
wght[i][j]=wght[j][i]=ed;
}
getch();
clrscr();
printf("\n\n\t\tNODES CURRENTLY ADDED TO SPANNING TREE\n\n");
buildtree();
printf("\n\tNEW GRAPH WEIGHT MATRIX\n\n");
printf("\n\tweight matrix\n\n\t");
for(i=0;i<n;i++,printf("\n\t"))
for(j=0;j<n;j++,printf("\t"))
printf("%d",new_wght[i][j]);
printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");
printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(new_wght[i][j]!=INF)
{
printf("\n\t\t%d ------ %d = %d ",vertex[i],vertex[j],new_wght[i][j]);
sum+=new_wght[i][j];}
printf("\n\n\t Total Weight : %d ",sum);
getch();
}
80
ADVANCED DATASTRUCTURES LAB MANUAL
EXPECTED OUTPUT:
Getting Weight:
Enter 0 if path doesn’t exist between {v1,v2} else enter the wght
1--------2:2
2--------3:4
1--------4:3
1--------5:0
2--------3:0
2--------4:2
2--------5:1
3--------4:1
3--------5:0
4--------5:4
Weight matrix
LIST OF EDGES
1------2=2
2------4=2
2------5=1
3------4=1
Total Weight:6
81
ADVANCED DATASTRUCTURES LAB MANUAL
EXERSICE10:
AIM: To implement Dijkstra’s algorithm to find shortest path in the graph.
DESCRIPTION:
DIJKSTRA’S Algorithm:For finding shortest path by using Dijkstra’s algorithm we have given
a weighted graph and we need to find out minimum distance route between any given two
stations
Algorithm:
Step1:select the source node and mark it as processed
Step2: select all the stations i.e neighbours of source station and mark them as ready and
update their mininmum distances as the distances from source
Step3:Repeat step4 till destination station status becomes processed
Step4:Select the station which is having minimum distance out of the stations which are in
the ready status.Make status of selected station as processed and update all of its
unprocessed,and update ready state nodes minimum distance by adding distance from
selected station to that station and distance of selected station from source
82
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/*program to implement dijkstra’s algorithm using priority queue*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int dist[10][10],sta[10],min[10],via[10];
int i,j,k,source,dest,amin,n,dd,t;
printf("Enter Number Of Nodes");
scanf("%d",&n);
printf("Enter Weights");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&dist[i][j]);
for(i=0;i<n;i++)
{
sta[i]=0;
min[i]=32767;
}
printf("Enter Source AND Destination indexes");
scanf("%d%d",&source,&dest);
k=source;
amin=0;
while(sta[dest]!=2)
{
sta[k]=2;
for(i=0;i<n;i++)
{
if(dist[k][i]&&sta[i]!=2)
{
dd=amin+dist[k][i];
83
ADVANCED DATASTRUCTURES LAB MANUAL
if(dd<min[i])
{
min[i]=dd;
via[i]=k;
}
sta[i]=1;
}
}
amin=32767;
for(i=0;i<n;i++)
if(sta[i]==1 && min[i]<amin)
{
amin=min[i];
k=i;
}
}
printf("Backtracking");
printf("%c->",'A'+dest);
for(k=via[dest];k!=source;k=via[k])
printf("%c->",'A'+k);
printf("%c",'A'+source);
return 0;
}
84
ADVANCED DATASTRUCTURES LAB MANUAL
EXPECTED OUTPUT:
85
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE-11:
AIM: To implement BOYER-Moore algorithm for pattern matching.
DESCRIPTION: The Boyer-Moore algorithm scans the characters of the pattern from right to
left beginning with the rightmost character. During the testing of a possible placement of
pattern P against text T, a mismatch of text character T[i] = c with the corresponding pattern
character P[j] is handled as follows: If c is not contained anywhere in P, then shift the
pattern P completely past T[i]. Otherwise, shift P until an occurrence of character c in P gets
aligned with T[i].This technique likely to avoid lots of needless comparisons by significantly
shifting pattern relative to text.
Last Function: We define a function last(c) that takes a character c from the alphabet and
specifies how far may shift the pattern P if a character equal to c is found in the text that
does not match the pattern
index of the last
if c is in P
occurrence
last(c
of c in pattern P
)
-1 otherwise
0 1 2 3 4 5 6 7 8 9
T:
a b a c A A B A C C
a b a C A B
P:
0 1 2 3 4 5
'd' does not exist in the pattern there we have last (d) = -1.
c A B C D
last(c) 4 3 -1
T: a b A C A a B a C c
86
ADVANCED DATASTRUCTURES LAB MANUAL
P: a b A C A b
c A B C D
last(c) 4 5 3 -1
Boyer-Moore algorithm :
BOYER_MOORE_MATCHER (T, P)
87
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
#include<stdio.h>
#include<conio.h>
void preBmBc(char *x, int m, int bmBc[ ])
{
int i;
for (i = 0; i < ASIZE; ++i)
bmBc[i] = m;
for (i = 0; i < m - 1; ++i)
bmBc[x[i]] = m - i - 1;
}
void suffixes(char *x, int m, int *suff)
{
int f, g, i;
suff[m - 1] = m;
g = m - 1;
for (i = m - 2; i >= 0; --i)
{
if (i > g && suff[i + m - 1 - f] < i - g)
suff[i] = suff[i + m - 1 - f];
else {
if (i < g)
g = i;
f = i;
while (g >= 0 && x[g] == x[g + m - 1 - f])
--g;
suff[i] = f - g;
}
}
}
88
ADVANCED DATASTRUCTURES LAB MANUAL
89
ADVANCED DATASTRUCTURES LAB MANUAL
else
j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i);
}
}
void main( )
{
char *x,*y;
int bmBc[ ], bmGs[ ] ,*suff
char *p="advanced data structures";
char *q="nced";
int m=strlen(p);
int n=strlen(q);
}
EXPECTED OUTPUT:
Pattern nced is present in text:
inadvanced data structures
90
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE-12:
AIM: To implement Knuth-Morris-Pratt algorithm for pattern matching.
DESCRIPTION:
DEFINITION: The KMP algorithm compares the pattern to the text in left-to-right, but shifts
the pattern, P more intelligently than the brute-force algorithm. When a mismatch occurs,
what is the most we can shift the pattern so as to avoid redundant comparisons. The answer
is that the largest prefix of P[0..j] that is a suffix of P[1..j]
EXPLANATION:The Knuth–Morris–Pratt string searching algorithm searches for occurrences
of a "word" W within a main "text string" S by employing the observation that when a
mismatch occurs, the word itself embodies sufficient information to determine where the
next match could begin, thus bypassing re-examination of previously matched characters.
• performs the comparisons from left to right;
• preprocessing phase in O(m) space and time complexity;
• searching phase in O(n+m) time complexity (independent from the alphabet size);
91
ADVANCED DATASTRUCTURES LAB MANUAL
SAMPLE PROGRAM:
/*Program to implement Knuth-Morris-Pratt pattern matching */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void cp(char p[],int pp[])
{
int q,k,m;
m=strlen(p);
pp[1]=0;
k=0;
for(q=2;q<m;q++)
{
while(k>0 && p[k+1]!=p[q])
k=pp[k];
if(p[k+1]==p[q])
k=k+1;
pp[q]=k;
}
}
void kmp(char t[],char p[])
{
int pp[50],i,q,k,m,n;
n=strlen(t);
m=strlen(p);
cp(p,pp);
q=0;
for(i=1;i<n;i++)
{
92
ADVANCED DATASTRUCTURES LAB MANUAL
while(q>0 && p[q+1]!=t[i])
q=pp[q];
if(p[q+1]==t[i])
q++;
if(q==m-1)
{
printf("String Found");
break;
}
}
if(i==n)
printf("String Not Found");
}
void main()
{
char t[100],p[50];
clrscr();
printf("Enter Actual String");
scanf("%s",&t);
printf("Enter String To Be Found");
scanf("%s",&p);
kmp(t,p);
getch();
}
EXPECTED OUTPUT:
Enter Actual String:acaabcaaba
Enter String To Be Found:bca
String Found
Enter actual String:aaabbbacaaa
Enter String To Be Found:bca
String Not Found
93
ADVANCED DATASTRUCTURES LAB MANUAL
EXERCISE 13:
AIM: To implement a program for Radix sort
DESCRIPTION:
94