You are on page 1of 55

ADVANCED DATA STRUCTURES LAB (R16)

1. AIM : TO PERFORM VARIOUS OPERATIONS I.E, INSERTIONS AND DELETIONS ON AVL TREES
AVL Tree in C:
An AVL (Adelson-Velskii and Landis) tree is a height balance tree. These trees are binary search trees in
which the height of two siblings are not permitted to differ by more than one. i.e. [Height of the left sub
tree – Height of right sub tree] <= 1.
A C program is given below which performs various operations like creation, insertion, deletion and
printing for an AVL tree.
PROGRAMME:
#include<stdio.h>
#include<malloc.h>
#define CHANGED 0
#define BALANCED 1
int height;
struct bnode
{
int data,bfactor;
struct bnode *left,*right;
};
typedef struct bnode node;
node* getnode()
{
int size;
node* newnode;
size=sizeof(node);
newnode=(node*)malloc(size);
return(newnode);
}
void copynode(node *r,int data)
{
r->data=data;
r->left=NULL;
r->right=NULL;
r->bfactor=0;
}
void releasenode(node *p)
{
free(p);
}
node* searchnode(node *root,int data)
{
if(root!=NULL)
if(data<root->data)
root=searchnode(root->left,data);
else if(data>root->data)
root=searchnode(root->right,data);
return(root);
}
void lefttoleft(node **Pptr,node **Aptr)

RAGHU INSTITUTE OF TECHNOLOGY 1


ADVANCED DATA STRUCTURES LAB (R16)

{
node *p=*Pptr,*A=*Aptr;
printf("\nLeft to left AVL Rotation\n");
p->left=A->right;
A->right=p;
if(A->bfactor==0)
{
p->bfactor=1;
A->bfactor=-1;
height=BALANCED;
}
else
{
p->bfactor=0;
A->bfactor=0;
}
p=A;
*Pptr=p;
*Aptr=A;
}
void lefttoright(node **Pptr,node **Aptr, node **Bptr)
{
node *p=*Pptr, *A=*Aptr, *B=*Bptr;
printf("\n Left to Right AVL Rotation \n");
B=A->right;
A->right=B->left;
B->left=A;
p->left=B->right;
B->right=p;
if(B->bfactor==1)
p->bfactor=-1;
else
p->bfactor=0;
if(B->bfactor==-1)
A->bfactor=1;
else
A->bfactor=0;
B->bfactor=0;
p=B;
*Pptr=p;
*Aptr=A;
*Bptr=B;
}
void righttoright(node **Pptr, node **Aptr)
{
node *p=*Pptr, *A=*Aptr;
printf("\n Right to Right AVL Rotation \n");
p->right=A->left;

RAGHU INSTITUTE OF TECHNOLOGY 2


ADVANCED DATA STRUCTURES LAB (R16)

A->left=p;
if(A->bfactor==0)
{
p->bfactor=-1;
A->bfactor=1;
height=BALANCED;
}
else
{
p->bfactor=0;
A->bfactor=0;
}
p=A;
*Pptr=p;
*Aptr=A;
}
void righttoleft(node **Pptr, node **Aptr, node **Bptr)
{
node *p=*Pptr, *A=*Aptr, *B=*Bptr;
printf("\n Right to Left AVL Rotation \n");
B=A->left;
A->left=B->right;
B->right=A;
p->right=B->left;
B->left=p;
if(B->bfactor==-1)
p->bfactor=1;
else
p->bfactor=0;
if(B->bfactor==1)
A->bfactor=-1;
else
A->bfactor=0;
B->bfactor=0;
p=B;
*Pptr=p;
*Aptr=A;
*Bptr=B;
}
node* insertnode(int data,node* p)
{
node *A,*B;
if(p==NULL)
{
p=getnode();
copynode(p,data);
height=CHANGED;
return(p);

RAGHU INSTITUTE OF TECHNOLOGY 3


ADVANCED DATA STRUCTURES LAB (R16)

}
if(data<p->data)
{
p->left=insertnode(data,p->left);
if(height==CHANGED)
{
switch(p->bfactor)
{
case -1:
p->bfactor=0; //right heavy tree
height=BALANCED;
break;
case 0:
p->bfactor=1; //balanced tree
break;
case 1:
A=p->left;
if(A->bfactor==1)
lefttoleft(&p,&A);
else
lefttoright(&p,&A,&B);
height=BALANCED;
break;
}
}
}
if(data>p->data)
{
p->right=insertnode(data,p->right);
if(height==CHANGED)
{
switch(p->bfactor)
{
case 1:
p->bfactor=0; //left heavy trees
height=BALANCED;
break;
case 0:
p->bfactor=-1; //balanaced trees
break;
case -1:
A=p->right; //right heavy trees
if(A->bfactor==-1)
righttoright(&p,&A);
else
righttoleft(&p,&A,&B);
height=CHANGED;
break;

RAGHU INSTITUTE OF TECHNOLOGY 4


ADVANCED DATA STRUCTURES LAB (R16)

}
}
}
return(p);
}
void del(node **N,node **C)
{
node *T,*A,*B;
node **p;
T=(*N);
if((*N)->right!=NULL)
{
del(&((*N)->right),C);
if(height==CHANGED)
{
p=N;
switch((*p)->bfactor)
{
case -1:
(*p)->bfactor=0;
break;
case 0:
(*p)->bfactor=1;
height=BALANCED;
break;
case 1:
A=(*p)->left;
if(A->bfactor>=0)
lefttoleft(p,&A);
else
lefttoright(p,&A,&B);
break;
}
}
}
else
{
(*C)->data=(*N)->data;
(*N)=(*N)->left;
releasenode(T);
height=CHANGED;
}
}
void deletenode(int data,node **p)
{
node *A,*B,*C;
if(*p==NULL)
{

RAGHU INSTITUTE OF TECHNOLOGY 5


ADVANCED DATA STRUCTURES LAB (R16)

printf("\nAVL Tree is empty");


return;
}
if(data<(*p)->data)
{
deletenode(data,&((*p)->left));
if(height==CHANGED)
{
switch((*p)->bfactor)
{
case 1:
(*p)->bfactor=0;
break;
case 0:
(*p)->bfactor=1;
height=BALANCED;
break;
case -1:
A=(*p)->right;
if(A->bfactor<=0)
righttoright(p,&A);
else
righttoleft(p,&A,&B);
break;
}
}
}
else if(data>(*p)->data)
{
deletenode(data,&((*p)->right));
if(height==CHANGED)
{
switch((*p)->bfactor)
{
case -1:
(*p)->bfactor=0;
break;
case 0:
(*p)->bfactor=1;
height=BALANCED;
break;
case 1:
A=(*p)->left;
if(A->bfactor>=0)
lefttoleft(p,&A);
else
lefttoright(p,&A,&B);
break;

RAGHU INSTITUTE OF TECHNOLOGY 6


ADVANCED DATA STRUCTURES LAB (R16)

}
}
}
else
{
C=*p;
if(C->right==NULL)
{
*p=C->left;
height=CHANGED;
releasenode(C);
}
else if(C->left==NULL)
{
*p=C->right;
height=CHANGED;
releasenode(C);
}
else
{
del(&(C->left),&C);
if(height==CHANGED)
{
switch((*p)->bfactor)
{
case 1:
(*p)->bfactor=0;
break;
case 0:
(*p)->bfactor=-1;
height=BALANCED;
break;
case -1:
A=(*p)->right;
if(A->bfactor<=0)
righttoright(p,&A);
else
righttoleft(p,&A,&B);
break;
}
}
}
}
}
void inorder(node *root)
{
if(root==NULL)
return;

RAGHU INSTITUTE OF TECHNOLOGY 7


ADVANCED DATA STRUCTURES LAB (R16)

inorder(root->left);
printf("%4d",root->data);
inorder(root->right);
}
void main()
{
int data,ch,choice='y';
node *root=NULL;
printf("\nBasic operations in an AVL Tree...");
printf("\n1.Insert a node in the AVL Tree");
printf("\n2.Delete a node in the AVL Tree");
printf("\n3.View the AVL Tree");
printf("\n4.Exit");
while((choice=='y')||(choice=='Y'))
{
printf("\n");
fflush(stdin);
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the value to be inserted:");
scanf("%d",&data);
if(searchnode(root,data)==NULL)
root=insertnode(data,root);
else
printf("\nData already exists");
break;
case 2:
printf("Enter the value to be deleted:");
scanf("%d",&data);
if(searchnode(root,data)!=NULL)
deletenode(data,&root);
else
printf("\nElement to be deleted is not found");
break;
case 3:
if(root==NULL)
{
printf("\nAVL Tree is Emoty\n");
continue;
}
printf("\nInorder Traversal of the AVL Tree:");
inorder(root);
break;
default:
printf("\nEnd of run of your program...");
releasenode(root);

RAGHU INSTITUTE OF TECHNOLOGY 8


ADVANCED DATA STRUCTURES LAB (R16)

return;
}
}
}

OUTPUT:
Basic operations in an AVL Tree...
1.Insert a node in the AVL Tree
2.Delete a node in the AVL Tree
3.View the AVL Tree
4.Exit
1
Enter the value to be inserted:23
1
Enter the value to be inserted:15
3
Inorder Traversal of the AVL Tree: 15 23
1
Enter the value to be inserted:13
Left to left AVL Rotation
3
Inorder Traversal of the AVL Tree: 13 15 23
1
Enter the value to be inserted:27
1
Enter the value to be inserted:20
1
Enter the value to be inserted:18
Right to Left AVL Rotation
Enter the value to be inserted:32
Right to Right AVL Rotation
3
Inorder Traversal of the AVL Tree: 13 15 18 20 23 27 32
Enter the value to be inserted:9
1
Enter the value to be inserted:12
Left to Right AVL Rotation
3
Inorder Traversal of the AVL Tree: 9 12 13 15 18 20 23 27 32

RAGHU INSTITUTE OF TECHNOLOGY 9


ADVANCED DATA STRUCTURES LAB (R16)

2. AIM: To implement operations on binary heap


PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define arraylength 20
int heapsize=0,heap[arraylength];
void enqueue(int element)
{
int currentnode;
if(heapsize==arraylength-1)
{
printf("Array is full");
return;
}
currentnode=++heapsize;
while(currentnode!=0&&heap[currentnode/2]<element)
{
heap[currentnode]=heap[currentnode/2];
currentnode/=2;
}
heap[currentnode]=element;
}
void dequeue()
{
int lastelement,currentnode,child;
if(heapsize==0)
{
printf("Priority queue is empty");
return;
}
heap[0]=0;
lastelement=heap[heapsize--];
currentnode=1;
child=2;
while(child<=heapsize)
{
if(child<heapsize&&heap[child]<heap[child+1])
child++;
if(lastelement>=heap[child])
break;
heap[currentnode]=heap[child];
currentnode=child;
child*=2;
}
heap[currentnode]=lastelement;
}

RAGHU INSTITUTE OF TECHNOLOGY 10


ADVANCED DATA STRUCTURES LAB (R16)

void display()
{
int i;
for(i=0;i<arraylength;i++)
{
printf("%5d",heap[i]);
}
}
void main()
{
int opt,ele;
while(1)
{
clrscr();
printf("\n.............");
printf("\n1.Enqueue");
printf("\n2.Dequeue");
printf("\n3.Display");
printf("\n4.Exit");
printf("\n............");
printf("\nEnter ur option:");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("Enter the element to insert:");
scanf("%d",&ele);
enqueue(ele);
break;
case 2:
dequeue();
printf("Element is deleted");
break;
case 3:
display();
break;
case 4:
exit(0);
}
getch();
} }
OUTPUT:

............. ............ 1.Enqueue


1.Enqueue Enter ur option:1 2.Dequeue
2.Dequeue Enter the element 3.Display
3.Display to insert: 10 4.Exit
4.Exit ............. ............

RAGHU INSTITUTE OF TECHNOLOGY 11


ADVANCED DATA STRUCTURES LAB (R16)

Enter ur option:1 Enter the element .............


Enter the element to insert: 18 1.Enqueue
to insert: 5 ............. 2.Dequeue
............. 1.Enqueue 3.Display
1.Enqueue 2.Dequeue 4.Exit
2.Dequeue 3.Display ............
3.Display 4.Exit Enter ur option:3
4.Exit ............ 24 18 10 5 0
............ Enter ur option:1 0 0 0 0 0
Enter ur option:1 Enter the element 0 0 0 0 0 0
to insert: 24 0 0 0 0
AIM: To implement operations on graphs
i) vertex insertion ii) Vertex deletion iii) finding vertex
iv)Edge addition and deletion

PROGRAM:
/*Program to create,insert,delete and view the adjecency matrix*/
#include<stdio.h>
#include<conio.h>
#define VSIZE 20
int checkWt();
int checkDir();
void insertVertex ();
void deleteVertex(int vDel);
void insertEdge(int vStart,int vEnd);
void deleteEdge(int vStart, int vEnd);
void createGraph();
void viewGraph();
void display_menu();
int nVertex,adjMat[VSIZE][VSIZE];
void main()
{
char choice='y';
int ch,vs,ve,vd;
clrscr();
display_menu();
while((choice=='y')||(choice=='y'))

RAGHU INSTITUTE OF TECHNOLOGY 12


ADVANCED DATA STRUCTURES LAB (R16)

{ printf("\n?");
fflush(stdin);
scanf("%d",&ch);
switch(ch)
{
case 0 :display_menu();
break;
case 1 :createGraph();
break;
case 2 :insertVertex();
break;
case 3 :printf("\n enter the starting & ending
vertex to insert an edge :");
scanf("%d %d",&vs,&ve);
insertEdge(vs,ve);
break;
case 4 :printf("\n enter the vertex to delete :");
scanf("%d",&vd);
deleteVertex(vd);
break;
case 5 :printf("\n enter the starting & ending
vertex to delete an edge :");
scanf("%d%d",&vs,&ve);
break;
case 6 :viewGraph();
break;
case 7 :printf("\n end of run of your
program...........");
exit(0);
}
}
}
void insertVertex()
{ int rc;
nVertex++;
for(rc=0;rc<nVertex;rc++)
adjMat[rc] [nVertex-1]=adjMat[nVertex-1] [rc]=0;

RAGHU INSTITUTE OF TECHNOLOGY 13


ADVANCED DATA STRUCTURES LAB (R16)

}
void insertEdge(int vStart,int vEnd)
{ int ie;
if(vStart>nVertex||vStart<1||vEnd>nVertex||vEnd<1)
return;
printf("enter weight of the Edge from v%d to v%d :", vStart
,vEnd);
scanf("%d",&adjMat [vStart-1] [vEnd-1]);
}
void deleteVertex(int vDel)
{ int r,c;
if(vDel>nVertex || vDel<1)
return;
for(r=vDel-1;r<nVertex; r++)
for(c=0;c<nVertex;c++)
adjMat[r][c]=adjMat[r+1][c];
for(c=vDel-1;r<nVertex;c++)
for(r=0;r<nVertex;r++)
adjMat[r][c]=adjMat[r][c+1];
nVertex--;
}
void deleteEdge(int vStart,int vEnd)
{ if(vStart>nVertex || vStart<1 || vEnd>nVertex|| vEnd<1)
return;
if(!checkDir()) adjMat [vStart-1] [vEnd-1] =0;
}
int checkDir()
{ int r,c;
for(r=0;r<nVertex;r++)
for(c=0;c<nVertex;c++)
if(adjMat[r][c]!=adjMat[c][r])
return 1;
return 0;
}
int checkWt()
{ int r,c;
for(r=0;r<nVertex;r++)

RAGHU INSTITUTE OF TECHNOLOGY 14


ADVANCED DATA STRUCTURES LAB (R16)

for(c=0;c<nVertex;c++)
if(adjMat[r][c]>1)
return 1;
return 0;
}
void createGraph()
{ int r,c;
printf("\n enter the no. of vertices : ");
scanf("%d",&nVertex);
for(r=0;r<nVertex;r++)
for(c=0;c<nVertex;c++)
{ adjMat[r][c]=0;
if(r!=c)
insertEdge(r+1,c+1);
}
}
void viewGraph()
{
int v,r,c,edge,inDeg[VSIZE],outDeg[VSIZE];
for(v=0;v<nVertex;v++)
printf(" v%d",v+1);
for(r=0;r<nVertex;r++)
{ printf("\nv%-2d ",r+1);
for(c=0;c<nVertex;c++)
printf("%-2d ",adjMat[r][c]);
}
for(v=0;v<nVertex;v++)
inDeg[v]=outDeg[v]=0;
edge=0;
for(r=0;r<nVertex;r++)
for(c=0;c<nVertex;c++)
if(adjMat[r][c]!=0)
{ edge++;
outDeg[r]++;
inDeg[c]++;
}
if(!checkDir())

RAGHU INSTITUTE OF TECHNOLOGY 15


ADVANCED DATA STRUCTURES LAB (R16)

edge=edge/2;
printf("n %s
Graph",(checkDir())?"DIRECTED" : "UNDIRECTED");
printf("n %s
Graph",(checkDir())?"Weighted" : "UNWeighted");
printf("total no. of vertices
:%d",nVertex);
printf("\ntotal no.of Edges : %d",edge);
printf("Vertex Indegree Outdegree");
for(r=0;r<nVertex;r++)
{ printf("\n v%-2d %-9d
%-9d",r+1,inDeg[r],outDeg[r]);
if(inDeg[r]==0 && outDeg[r]!=0)
printf(":
%s","SOURE");
if(inDeg[r]!=0 && outDeg[r]==0)
printf(":
%s","SKIN");
if(inDeg[r]==1 &&
outDeg[r]==0)
printf(":
%s","PENDANT");
if(inDeg[r]==0 &&
outDeg[r]==0)
printf(":
%s","ISOLATED");
}
}
void display_menu()
{
printf("\n\n basic operation in an adjacency matrix..........");
printf("\n\t 0. Display Menu");
printf("\n\t 1.Creation of Graph");
printf("\n\t 2. Insert a Vertex");
printf("\n\t 3. Insert an Edge");
printf("\n\t 4. Delete aVertex");
printf("\n\t 5. Delete an Edge ");

RAGHU INSTITUTE OF TECHNOLOGY 16


ADVANCED DATA STRUCTURES LAB (R16)

printf("\n\t 6. Veiw the Graph");


printf("\n\t 7. Exit");
}
OUTPUT:

basic operation in an adjacency matrix.......... v1 v2 v3 v4 v5


0. Display Menu v1 0 1 0 1 1
1.Creation of Graph v2 1 0 1 1 0
2. Insert a Vertex v3 0 1 0 1 1
3. Insert an Edge v4 1 1 1 0 1
4. Delete aVertex v5 1 0 1 1 0
5. Delete an Edge n UNDIRECTED Graphn UNWeighted G
6. Veiw the Graph raphtotal no. of vertices :5
7. Exit total no.of Edges : 8Vertex Indegree Outdegree
?1 v1 3 3
v2 3 3
enter the no. of vertices : 5 v3 3 3
enter weight of the Edge from v1 to v2 :1 v4 4 4
enter weight of the Edge from v1 to v3 :0 v5 3 3
enter weight of the Edge from v1 to v4 :1 ?7
enter weight of the Edge from v1 to v5 :1
enter weight of the Edge from v2 to v1 :1
enter weight of the Edge from v2 to v3 :1
enter weight of the Edge from v2 to v4 :1
enter weight of the Edge from v2 to v5 :0
enter weight of the Edge from v3 to v1 :0
enter weight of the Edge from v3 to v2 :1
enter weight of the Edge from v3 to v4 :1
enter weight of the Edge from v3 to v5 :1
enter weight of the Edge from v4 to v1 :1
enter weight of the Edge from v4 to v2 :1
enter weight of the Edge from v4 to v3 :1
enter weight of the Edge from v4 to v5 :1
enter weight of the Edge from v5 to v1 :1
enter weight of the Edge from v5 to v2 :0
enter weight of the Edge from v5 to v3 :1
enter weight of the Edge from v5 to v4 :1

RAGHU INSTITUTE OF TECHNOLOGY 17


ADVANCED DATA STRUCTURES LAB (R16)

3. AIM: C Program to find a minimum spanning tree using Prim’s algorithm


Prim’s Algorithm is an approach to determine minimum cost spanning tree. In this case, we start
with single edge of graph and we add edges to it and finally we get minimum cost tree. In this case,
as well, we have n-1 edges when number of nodes in graph are n.We again and again add edges to
tree and tree is extended to create spanning tree, while in case of Kruskal’s algorithm there may be
more than one tree, which is finally connected through edge to create spanning tree.
Algorithm
This algorithm creates spanning tree with minimum weight from a given weighted graph.
1. Begin
2. Create edge list of given graph, with their weights.
3. Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
5. Add other edges. While adding an edge take care that the one end of the edge should
always be in the skeleton tree and its cost should be minimum.
6. Repeat step 5 until n-1 edges are added.
7. Return.

PROGRAMME:
#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");


for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}

//initialise visited[],distance[] and from[]


distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];

//insert the edge in spanning tree


spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

Output:
Enter no. of vertices:6
Enter the adjacency matrix:
031600
305030
150564
605002
036006
004260
spanning tree matrix:
031000
300030
100004
000002
030000
004200
Total cost of spanning tree=13

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

4. AIM: To implement Krushkal’s algorithm to generate a min-cost spanning tree.

Kruskal’s Algorithm
This algorithm will create spanning tree with minimum weight, from a given weighted graph.
1. Begin
2. Create the edge list of given graph, with their weights.
3. Sort the edge list according to their weights in ascending order.
4. Draw all the nodes to create skeleton for spanning tree.
5. Pick up the edge at the top of the edge list (i.e. edge with minimum weight).
6. Remove this edge from the edge list.
7. Connect the vertices in the skeleton with given edge. If by connecting the vertices, a cycle is
created in the skeleton, then discard this edge.
8. Repeat steps 5 to 7, until n-1 edges are added or list of edges is over.
9. Return

PROGRAMME:
#include<stdio.h>
#define MAX 30
typedef struct edge
{
int u,v,w;
}edge;

typedef struct edgelist


{
edge data[MAX];
int n;
}edgelist;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

edgelist elist;

int G[MAX][MAX],n;
edgelist spanlist;

void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();

void main()
{
int i,j,total_cost;

printf("\nEnter number of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

kruskal();
print();
}

void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;

for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}

sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}

int find(int belongs[],int vertexno)


{
return(belongs[vertexno]);
}

void union1(int belongs[],int c1,int c2)


{
int i;

for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}

void sort()
{
int i,j;
edge temp;

for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}

void print()
{
int i,cost=0;

for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

printf("\n\nCost of the spanning tree=%d",cost);


}

OUTPUT:

Time Complexity of Kruskal’s Algorithm


Let us assume a graph with e number of edges and n number of vertices. Kruskal’s algorithm starts
with sorting of edges.
Time complexity of sorting algorithm= O (e log e)

In Kruskal’s algorithm, we have to add an edge to the spanning tree, in each iteration. This involves
merging of two components.

Time complexity of merging of components= O (e log n)

Overall time complexity of the algorithm= O (e log e) + O (e log n)

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

5. AIM: To implement Dijkstra’s algorithm to find shortest path in the graph.

Dijkstra algorithm is also called single source shortest path algorithm. It is based on greedy
technique. The algorithm maintains a list visited [ ] of vertices, whose shortest distance from the
source is already known.
If visited [1], equals 1, then the shortest distance of vertex i is already known. Initially, visited[i] is
marked as, for source vertex.
At each step, we mark visited[v] as 1. Vertex v is a vertex at shortest distance from the source vertex.
At each step of the algorithm, shortest distance of each vertex is stored in an array distance [ ].

Dijkstra’s Algorithm
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex i to
vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
2. Array visited[ ] is initialized to zero.
for(i=0;i<n;i++)
visited[i]=0;
3. If the vertex 0 is the source vertex then visited[0] is marked as 1.
4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;

5. for(i=1;i<n;i++)
– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
– Recalculate the shortest distance of remaining vertices from the source.
– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of
distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
Time Complexity
The program contains two nested loops each of which has a complexity of O(n). n is number of
vertices. So the complexity of algorithm is O(n2).

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

PROGRAMME:
#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)

for(j=0;j<n;j++)

scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

return 0;

void dijkstra(int G[MAX][MAX],int n,int startnode)

int cost[MAX][MAX],distance[MAX],pred[MAX];

int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far

//create the cost matrix

for(i=0;i<n;i++)

for(j=0;j<n;j++)

if(G[i][j]==0)

cost[i][j]=INFINITY;

else

cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]

for(i=0;i<n;i++)

distance[i]=cost[startnode][i];

pred[i]=startnode;

visited[i]=0;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

distance[startnode]=0;

visited[startnode]=1;

count=1;

while(count<n-1)

mindistance=INFINITY;

//nextnode gives the node at minimum distance

for(i=0;i<n;i++)

if(distance[i]<mindistance&&!visited[i])

mindistance=distance[i];

nextnode=i;

//check if a better path exists through nextnode

visited[nextnode]=1;

for(i=0;i<n;i++)

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

distance[i]=mindistance+cost[nextnode][i];

pred[i]=nextnode;

count++;

//print the path and distance of each node

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

for(i=0;i<n;i++)

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do

j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

OUTPUT:

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

6. AIM: To implementation of Static Hashing (Use Linear probing for collision resolution)

Closed Hashing - Linear Probing

 Linear Probing resolves hash collision(same hash value for two or more data).

 It allows user to get the free space by searching the hash table sequentially.

To insert an element into the hash table, we need to find the hash index from the given key.
Example: hashIndex = key % tableSize (hash table size)

If the resultant hash index is already occupied by another data, we need to do linear probing to find
a free space in hash table.
Example: hashIndex = (key + i) % tableSize where i = 0,1,2...

To delete an element from the hash table, we need to calculate the hash index from the given key.
hashIndex = key % tableSize

If the given key is not available at the resultant hash index, we need to probe forward until we
encounter the given key or the value '0' for marker.

If the marker of any bucket is 0, then the given data is not present in the hash table. If we encounter
the given key in the hash table, then delete it and set the marker value to -1.

What is the purpose of marker in linear probing?


Just for example, try to insert the keys 21, 32 and 31 into the hash table.

hashIndex = key % tableSize(5)


hashIndex for 21 = 21 % 5 = 1
hashIndex for 32 = 32 % 5 = 2
hashIndex for 31 = 31 % 5 = 1

We are getting collision for data 31 because index 1 is already occupied by 21. So, we need to check
the next available location by doing linear probing.

Check for next available location(for key 31)


hashIndex = (key + i) % 5 where i=0,1,2,...
hashIndex for 31 = (31 + 1) % 5 = 2

Hash index 2 is also occupied already. So, we need to check for the next available location.
hashIndex for 31 = (31+2) % 5 = 3.

Hash index 3 is not occupied. So, we can insert key 31 in the third bucket.

Suppose if user deletes 32 and then he wants to delete 31. We will get hash index as 1 for the key
31. But, the bucket at hash index 1 holds the data 21. So, we will check the next bucket((31 +1) % 5
= 2nd bucket) and it would be empty. So, we might think that either the key 31 is not present or it's
already gone. In order to avoid that, we will set the marker to -1 which indicates that the data we
search might be present in the subsequent buckets.

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

PROGRAMME:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int tableSize = 0, totEle = 0;


struct node *hashTable = NULL;

struct node {
int age, key;
char name[100];
int marker;
};

void insertInHash(int key, char *name, int age) {


int hashIndex = key % tableSize;
if (tableSize == totEle) {
printf("Can't perform Insertion..Hash Table is full!!");
return;
}
while (hashTable[hashIndex].marker == 1) {
hashIndex = (hashIndex + 1)%tableSize;
}
hashTable[hashIndex].key = key;
hashTable[hashIndex].age = age;
strcpy(hashTable[hashIndex].name, name);
hashTable[hashIndex].marker = 1;
totEle++;
return;
}

void deleteFromHash(int key) {

int hashIndex = key % tableSize, count = 0, flag = 0;

if (totEle == 0) {

printf("Hash Table is Empty!!\n");

return;

while (hashTable[hashIndex].marker != 0 && count <= tableSize) {

if (hashTable[hashIndex].key == key) {

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

hashTable[hashIndex].key = 0;

/* set marker to -1 during deletion operation*/

hashTable[hashIndex].marker = -1;

hashTable[hashIndex].age = 0;

strcpy(hashTable[hashIndex].name, "\0");

totEle--;

flag = 1;

break;

hashIndex = (hashIndex + 1)%tableSize;

count++;

if (flag)

printf("Given data deleted from Hash Table\n");

else

printf("Given data is not available in Hash Table\n");

return;

void searchElement(int key) {

int hashIndex = key % tableSize, flag = 0, count = 0;

if (totEle == 0) {

printf("Hash Table is Empty!!");

return;

while (hashTable[hashIndex].marker != 0 && count <= tableSize) {

if (hashTable[hashIndex].key == key) {

printf("Voter ID : %d\n", hashTable[hashIndex].key);

printf("Name : %s\n", hashTable[hashIndex].name);

printf("Age : %d\n", hashTable[hashIndex].age);

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

flag = 1;

break;

hashIndex = (hashIndex + 1)%tableSize;

if (!flag)

printf("Given data is not present in hash table\n");

return;

void display() {

int i;

if (totEle == 0) {

printf("Hash Table is Empty!!\n");

return;

printf("Voter ID Name Age Index \n");

printf("-----------------------------------------\n");

for (i = 0; i < tableSize; i++) {

if (hashTable[i].marker == 1) {

printf("%-13d", hashTable[i].key);

printf("%-15s", hashTable[i].name);

printf("%-7d", hashTable[i].age);

printf("%d\n", i);

printf("\n");

return;

int main() {

int key, age, ch;

char name[100];

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

printf("Enter the no of elements:");

scanf("%d", &tableSize);

hashTable = (struct node *)calloc(tableSize, sizeof(struct node));

while (1) {

printf("1. Insertion\t2. Deletion\n");

printf("3. Searching\t4. Display\n");

printf("5. Exit\nEnter ur choice:");

scanf("%d", &ch);

switch (ch) {

case 1:

printf("Enter the key value:");

scanf("%d", &key);

getchar();

printf("Name:");

fgets(name, 100, stdin);

name[strlen(name) - 1] = '\0';

printf("Age:");

scanf("%d", &age);

insertInHash(key, name, age);

break;

case 2:

printf("Enter the key value:");

scanf("%d", &key);

deleteFromHash(key);

break;

case 3:

printf("Enter the key value:");

scanf("%d", &key);

searchElement(key);

break;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

case 4:

display();

break;

case 5:

exit(0);

default:

printf("U have entered wrong Option!!\n");

break;

return 0;

Output:
Enter the no of elements:3
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:1
Enter the key value:1
Name:Harry
Age:23
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:1
Enter the key value:2
Name:Ram
Age:24
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:1
Enter the key value:3
Name:Raj
Age:23
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:4
Voter ID Name Age Index
-----------------------------------------

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

3 Raj 23 0
1 Harry 23 1
2 Ram 24 2

1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:2
Enter the key value:1
Given data deleted from Hash Table
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:4
Voter ID Name Age Index
-----------------------------------------
3 Raj 23 0
2 Ram 24 2

1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:1
Enter the key value:10
Name:Ravi
Age:23
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:4
Voter ID Name Age Index
-----------------------------------------
3 Raj 23 0
10 Ravi 23 1
2 Ram 24 2

1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:3
Enter the key value:10
Voter ID : 10
Name : Ravi
Age : 23
1. Insertion 2. Deletion
3. Searching 4. Display
5. Exit
Enter ur choice:5

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

7.)AIM: To implement of Huffmann coding.

Huffman coding is a compression method which generates variable-length codes for data – the more
frequent the data item, the shorter the code generated. This allows more efficient compression than
fixed-length codes. This is an implementation of the algorithm in C. The function huffman() takes
arrays of letters and their frequencies, the length of the arrays, and a callback which is called for
each code generated. The algorithm requires a priority queue, and I used a min-heap for the
purpose.
PROGRAMME:

#include <stdlib.h>

#include <minheap.h>

struct huffman_node {

char data;

unsigned int frequency;

struct huffman_node *left;

struct huffman_node *right;

};

typedef struct huffman_node huffman_node;

huffman_node *huffman_node_create(char data, unsigned int frequency)

huffman_node *node = malloc(sizeof(huffman_node));

if (node) {

node->data = data;

node->frequency = frequency;

node->left = NULL;

node->right = NULL;

return node;

void huffman_node_delete(huffman_node *node)

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

if (node) {

huffman_node_delete(node->left);

huffman_node_delete(node->right);

free(node);

unsigned int max(unsigned int a, unsigned int b)

return a > b ? a : b;

unsigned int huffman_node_height(const huffman_node *node)

unsigned int height = 0;

if (node->left || node->right) {

height = max(node->left ? huffman_node_height(node->left) : 0,

node->right ? huffman_node_height(node->right) : 0) + 1;

return height;

void huffman_node_print(const huffman_node *node, unsigned int indent)

unsigned int i;

for (i = 0; i < indent; i++) {

printf(" ");

printf("%c %u\n", node->data, node->frequency);

if (node->left != NULL) {

huffman_node_print(node->left, indent + 1);

if (node->right != NULL) {

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

huffman_node_print(node->right, indent + 1);

typedef void huffmanfn(char, const unsigned int *, size_t);

void huffman_node_encodings(const huffman_node *node, unsigned int *arr,

unsigned int pos, huffmanfn fun)

if (node->left) {

arr[pos] = 0;

huffman_node_encodings(node->left, arr, pos + 1, fun);

if (node->right) {

arr[pos] = 1;

huffman_node_encodings(node->right, arr, pos + 1, fun);

if (!(node->left || node->right)) {

fun(node->data, arr, pos);

void huffman(const char *letters, const int *frequencies, size_t size, huffmanfn fun)

minheap *heap = minheap_create();

unsigned int i;

huffman_node *top;

unsigned int *arr;

/* Populate the heap */

for (i = 0; i < size; i++) {

minheap_add(heap, huffman_node_create(letters[i], frequencies[i]), frequencies[i]);

/* Build the tree */

while (minheap_get_count(heap) != 1) {

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

huffman_node *left = minheap_remove_min(heap);

huffman_node *right = minheap_remove_min(heap);

top = huffman_node_create('$', left->frequency + right->frequency);

top->left = left;

top->right = right;

minheap_add(heap, top, top->frequency);

top = minheap_remove_min(heap);

/* Generate the encodings */

arr = malloc(huffman_node_height(top) * sizeof(unsigned int));

huffman_node_encodings(top, arr, 0, fun);

/* Clean up */

huffman_node_delete(top);

free(arr);

minheap_delete(heap);

Example program:

void print(char letter, const unsigned int *arr, size_t len)

unsigned int i;

printf("%c: ", letter);

for (i = 0; i < len; i++) {

printf("%u", arr[i]);

putchar('\n');

int main(void)

char letters[] = {'a', 'b', 'c', 'd', 'e', 'f'};

int frequencies[] = {45, 13, 12, 16, 9, 5};

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

const size_t size = sizeof(letters) / sizeof(letters[0]);

huffman(letters, frequencies, size, print);

return 0;

OUT PUT:

a: 0

c: 100

b: 101

f: 1100

e: 1101

d: 111

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

8. AIM: To implement of B-tree.

C Program To Perform Insertion, Deletion and Traversal In B-Tree

 B- tree is a multiway search tree. A node in B-tree of order n can have at most n-1 values
and n children.

 All values that appear on the left sub-tree are smaller than left most value in the parent
node.

 All values that appear on the right sub-tree are greater than right most value in the parent
node.

 All values that appear on the middle sub-tree are greater than leftmost value in parent node
and smaller than right most value in parent node.

Example for B-tree of Order 3:


70
/ \
17 67 89
/ | \ / \
12 15 29 69 75 92 99

Above is an example for B-Tree of order 3.

 An intermediate node can have 2 or 3 children.

 Any node can have at most 1 or 2 values.

 Nodes on the left sub-tree are smaller than the left most value in parent node.

 Nodes on the right sub-tree are greater than the right most value in parent node.

 Nodes on the middle sub-tree are smaller than left most value and greater than right most
value in parent node.

Searching in B-Tree:

70
/ \
17 67 89
/ | \ / \
12 15 29 69 75 92 99

Search the value 29 in above B-Tree.


29 < 70 - So, search in left sub-tree of 70
29 > 17 && 29 < 67 - So, search in middle sub-tree.
29 is the middle child of 17 & 67.

Insertion in B-Tree:

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

70
/ \
17 67 89
/ | \ / \
12 15 29 69 75 92 99

Insert the value 10 to the above B-Tree.


Find the appropriate position to insert the given value in B-Tree.
10 < 70 - Search in left sub-tree of 70.
10 < 17 - Search in left sub-tree of 17.

17 needs to be inserted in the left child of 17.

70
/ \
17 67 89
/ | \ / \
17 12 15 29 69 75 92 99

Now, the modified node has 3 values 17, 12 and 15. But, it violates the rule in B-Tree(any node in B-
Tree of order can have at most n-1 value).

To restore B-Tree, middle value of 17, 12 and 15 is moved to parent node. Then, split the resultant
node containing 17 and 15 into two nodes forming left and right sub-tree containing the value 17
and 15 correspondingly.

70
/ \
12 17 67 89
/ / | \ / \
17 15 29 69 75 92 99

Now, the parent node violates B-Tree definition. So, restore it.
70 17
/ | \
12 67 89
/ \ / \ / \
17 15 29 69 75 92 99

Deletion in B-Tree:

70
/ \
17 67 89
/ | \ / \
12 15 29 69 75 92 99

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

Delete 69 from the above B-Tree. Search the position of 69 to delete.


69 < 70 - Search in left sub-tree of 70
69 > 17 - Compare 69 with right most value in the search node.
60 > 67 - Search in right sub-tree of 67
69 is the right child of 67.

In case the node which we are trying to delete has only one value(69), then find the predecessor(29)
for it(69) and merge the predecessor with the sibiling(29) of the node to be deleted. Then, delete
the desired node.
70
/ \
17 89
/ \ / \
12 15 29 67 75 92 99

PROGRAMME:

#include <stdio.h>
#include <stdlib.h>
#define MAX 4
#define MIN 2
struct btreeNode {
int val[MAX + 1], count;
struct btreeNode *link[MAX + 1];
};

struct btreeNode *root;

/* creating new node */


struct btreeNode * createNode(int val, struct btreeNode *child) {
struct btreeNode *newNode;
newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));
newNode->val[1] = val;
newNode->count = 1;
newNode->link[0] = root;
newNode->link[1] = child;
return newNode;
}

/* Places the value in appropriate position */


void addValToNode(int val, int pos, struct btreeNode *node,
struct btreeNode *child) {
int j = node->count;
while (j > pos) {
node->val[j + 1] = node->val[j];
node->link[j + 1] = node->link[j];
j--;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

}
node->val[j + 1] = val;
node->link[j + 1] = child;
node->count++;
}

/* split the node */

void splitNode (int val, int *pval, int pos, struct btreeNode *node,

struct btreeNode *child, struct btreeNode **newNode) {

int median, j;

if (pos > MIN)

median = MIN + 1;

else

median = MIN;

*newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));

j = median + 1;

while (j <= MAX) {

(*newNode)->val[j - median] = node->val[j];

(*newNode)->link[j - median] = node->link[j];

j++;

node->count = median;

(*newNode)->count = MAX - median;

if (pos <= MIN) {

addValToNode(val, pos, node, child);

} else {

addValToNode(val, pos - median, *newNode, child);

*pval = node->val[node->count];

(*newNode)->link[0] = node->link[node->count];

node->count--;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

/* sets the value val in the node */

int setValueInNode(int val, int *pval,

struct btreeNode *node, struct btreeNode **child) {

int pos;

if (!node) {

*pval = val;

*child = NULL;

return 1;

if (val < node->val[1]) {

pos = 0;

} else {

for (pos = node->count;

(val < node->val[pos] && pos > 1); pos--);

if (val == node->val[pos]) {

printf("Duplicates not allowed\n");

return 0;

if (setValueInNode(val, pval, node->link[pos], child)) {

if (node->count < MAX) {

addValToNode(*pval, pos, node, *child);

} else {

splitNode(*pval, pval, pos, node, *child, child);

return 1;

return 0;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

/* insert val in B-Tree */

void insertion(int val) {

int flag, i;

struct btreeNode *child;

flag = setValueInNode(val, &i, root, &child);

if (flag)

root = createNode(i, child);

/* copy successor for the value to be deleted */

void copySuccessor(struct btreeNode *myNode, int pos) {

struct btreeNode *dummy;

dummy = myNode->link[pos];

for (;dummy->link[0] != NULL;)

dummy = dummy->link[0];

myNode->val[pos] = dummy->val[1];

/* removes the value from the given node and rearrange values */

void removeVal(struct btreeNode *myNode, int pos) {

int i = pos + 1;

while (i <= myNode->count) {

myNode->val[i - 1] = myNode->val[i];

myNode->link[i - 1] = myNode->link[i];

i++;

myNode->count--;

/* shifts value from parent to right child */

void doRightShift(struct btreeNode *myNode, int pos) {

struct btreeNode *x = myNode->link[pos];

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

int j = x->count;

while (j > 0) {

x->val[j + 1] = x->val[j];

x->link[j + 1] = x->link[j];

x->val[1] = myNode->val[pos];

x->link[1] = x->link[0];

x->count++;

x = myNode->link[pos - 1];

myNode->val[pos] = x->val[x->count];

myNode->link[pos] = x->link[x->count];

x->count--;

return;

/* shifts value from parent to left child */

void doLeftShift(struct btreeNode *myNode, int pos) {

int j = 1;

struct btreeNode *x = myNode->link[pos - 1];

x->count++;

x->val[x->count] = myNode->val[pos];

x->link[x->count] = myNode->link[pos]->link[0];

x = myNode->link[pos];

myNode->val[pos] = x->val[1];

x->link[0] = x->link[1];

x->count--;

while (j <= x->count) {

x->val[j] = x->val[j + 1];

x->link[j] = x->link[j + 1];

j++;

return;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

/* merge nodes */

void mergeNodes(struct btreeNode *myNode, int pos) {

int j = 1;

struct btreeNode *x1 = myNode->link[pos], *x2 = myNode->link[pos - 1];

x2->count++;

x2->val[x2->count] = myNode->val[pos];

x2->link[x2->count] = myNode->link[0];

while (j <= x1->count) {

x2->count++;

x2->val[x2->count] = x1->val[j];

x2->link[x2->count] = x1->link[j];

j++;

j = pos;

while (j < myNode->count) {

myNode->val[j] = myNode->val[j + 1];

myNode->link[j] = myNode->link[j + 1];

j++;

myNode->count--;

free(x1);

/* adjusts the given node */

void adjustNode(struct btreeNode *myNode, int pos) {

if (!pos) {

if (myNode->link[1]->count > MIN) {

doLeftShift(myNode, 1);

} else {

mergeNodes(myNode, 1);

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

} else {

if (myNode->count != pos) {

if(myNode->link[pos - 1]->count > MIN) {

doRightShift(myNode, pos);

} else {

if (myNode->link[pos + 1]->count > MIN) {

doLeftShift(myNode, pos + 1);

} else {

mergeNodes(myNode, pos);

} else {

if (myNode->link[pos - 1]->count > MIN)

doRightShift(myNode, pos);

else

mergeNodes(myNode, pos);

/* delete val from the node */

int delValFromNode(int val, struct btreeNode *myNode) {

int pos, flag = 0;

if (myNode) {

if (val < myNode->val[1]) {

pos = 0;

flag = 0;

} else {

for (pos = myNode->count;

(val < myNode->val[pos] && pos > 1); pos--);

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

if (val == myNode->val[pos]) {

flag = 1;

} else {

flag = 0;

if (flag) {

if (myNode->link[pos - 1]) {

copySuccessor(myNode, pos);

flag = delValFromNode(myNode->val[pos], myNode->link[pos]);

if (flag == 0) {

printf("Given data is not present in B-Tree\n");

} else {

removeVal(myNode, pos);

} else {

flag = delValFromNode(val, myNode->link[pos]);

if (myNode->link[pos]) {

if (myNode->link[pos]->count < MIN)

adjustNode(myNode, pos);

return flag;

/* delete val from B-tree */

void deletion(int val, struct btreeNode *myNode) {

struct btreeNode *tmp;

if (!delValFromNode(val, myNode)) {

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

printf("Given value is not present in B-Tree\n");

return;

} else {

if (myNode->count == 0) {

tmp = myNode;

myNode = myNode->link[0];

free(tmp);

root = myNode;

return;

/* search val in B-Tree */

void searching(int val, int *pos, struct btreeNode *myNode) {

if (!myNode) {

return;

if (val < myNode->val[1]) {

*pos = 0;

} else {

for (*pos = myNode->count;

(val < myNode->val[*pos] && *pos > 1); (*pos)--);

if (val == myNode->val[*pos]) {

printf("Given data %d is present in B-Tree", val);

return;

searching(val, pos, myNode->link[*pos]);

return;

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

/* B-Tree Traversal */

void traversal(struct btreeNode *myNode) {

int i;

if (myNode) {

for (i = 0; i < myNode->count; i++) {

traversal(myNode->link[i]);

printf("%d ", myNode->val[i + 1]);

traversal(myNode->link[i]);

int main() {

int val, ch;

while (1) {

printf("1. Insertion\t2. Deletion\n");

printf("3. Searching\t4. Traversal\n");

printf("5. Exit\nEnter your choice:");

scanf("%d", &ch);

switch (ch) {

case 1:

printf("Enter your input:");

scanf("%d", &val);

insertion(val);

break;

case 2:

printf("Enter the element to delete:");

scanf("%d", &val);

deletion(val, root);

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

break;

case 3:

printf("Enter the element to search:");

scanf("%d", &val);

searching(val, &ch, root);

break;

case 4:

traversal(root);

break;

case 5:

exit(0);

default:

printf("U have entered wrong option!!\n");

break;

printf("\n");

OUT PUT:

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:70

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:17

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY


ADVANCED DATA STRUCTURES LAB (R16)

Enter your input:67

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:1
Enter your input:89

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:4
17 67 70 89

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:3
Enter the element to search:70
Given data 70 is present in B-Tree

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:2
Enter the element to delete:17

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:4
67 70 89

1. Insertion 2. Deletion
3. Searching 4. Traversal
5. Exit
Enter your choice:5

ADVANCED DATA STRUCTURES LAB(R16) RAGHU INSTITUTE OF TECHNOLOGY

You might also like