Professional Documents
Culture Documents
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)
{
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;
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);
}
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;
}
}
}
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)
{
}
}
}
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;
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);
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
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:
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'))
{ 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;
}
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++)
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())
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 ");
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);
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;
}
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
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;
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;
scanf("%d",&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++)
{
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);
}
}
}
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;
}
OUTPUT:
In Kruskal’s algorithm, we have to add an edge to the spanning tree, in each iteration. This involves
merging of two components.
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).
PROGRAMME:
#include<stdio.h>
#include<conio.h>
#define MAX 10
int main()
int G[MAX][MAX],i,j,n,u;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
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];
for(i=0;i<n;i++)
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
mindistance=distance[i];
nextnode=i;
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++;
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:
6. AIM: To implementation of Static Hashing (Use Linear probing for collision resolution)
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.
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.
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.
PROGRAMME:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int age, key;
char name[100];
int marker;
};
if (totEle == 0) {
return;
if (hashTable[hashIndex].key == key) {
hashTable[hashIndex].key = 0;
hashTable[hashIndex].marker = -1;
hashTable[hashIndex].age = 0;
strcpy(hashTable[hashIndex].name, "\0");
totEle--;
flag = 1;
break;
count++;
if (flag)
else
return;
if (totEle == 0) {
return;
if (hashTable[hashIndex].key == key) {
flag = 1;
break;
if (!flag)
return;
void display() {
int i;
if (totEle == 0) {
return;
printf("-----------------------------------------\n");
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() {
char name[100];
scanf("%d", &tableSize);
while (1) {
scanf("%d", &ch);
switch (ch) {
case 1:
scanf("%d", &key);
getchar();
printf("Name:");
name[strlen(name) - 1] = '\0';
printf("Age:");
scanf("%d", &age);
break;
case 2:
scanf("%d", &key);
deleteFromHash(key);
break;
case 3:
scanf("%d", &key);
searchElement(key);
break;
case 4:
display();
break;
case 5:
exit(0);
default:
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
-----------------------------------------
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
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;
};
if (node) {
node->data = data;
node->frequency = frequency;
node->left = NULL;
node->right = NULL;
return node;
if (node) {
huffman_node_delete(node->left);
huffman_node_delete(node->right);
free(node);
return a > b ? a : b;
if (node->left || node->right) {
node->right ? huffman_node_height(node->right) : 0) + 1;
return height;
unsigned int i;
printf(" ");
if (node->left != NULL) {
if (node->right != NULL) {
if (node->left) {
arr[pos] = 0;
if (node->right) {
arr[pos] = 1;
if (!(node->left || node->right)) {
void huffman(const char *letters, const int *frequencies, size_t size, huffmanfn fun)
unsigned int i;
huffman_node *top;
while (minheap_get_count(heap) != 1) {
top->left = left;
top->right = right;
top = minheap_remove_min(heap);
/* Clean up */
huffman_node_delete(top);
free(arr);
minheap_delete(heap);
Example program:
unsigned int i;
printf("%u", arr[i]);
putchar('\n');
int main(void)
return 0;
OUT PUT:
a: 0
c: 100
b: 101
f: 1100
e: 1101
d: 111
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.
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
Insertion in B-Tree:
70
/ \
17 67 89
/ | \ / \
12 15 29 69 75 92 99
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
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];
};
}
node->val[j + 1] = val;
node->link[j + 1] = child;
node->count++;
}
void splitNode (int val, int *pval, int pos, struct btreeNode *node,
int median, j;
median = MIN + 1;
else
median = MIN;
j = median + 1;
j++;
node->count = median;
} else {
*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;
int pos;
if (!node) {
*pval = val;
*child = NULL;
return 1;
pos = 0;
} else {
if (val == node->val[pos]) {
return 0;
} else {
return 1;
return 0;
int flag, i;
if (flag)
dummy = myNode->link[pos];
dummy = dummy->link[0];
myNode->val[pos] = dummy->val[1];
/* removes the value from the given node and rearrange values */
int i = pos + 1;
myNode->val[i - 1] = myNode->val[i];
myNode->link[i - 1] = myNode->link[i];
i++;
myNode->count--;
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;
int j = 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--;
j++;
return;
/* merge nodes */
int j = 1;
x2->count++;
x2->val[x2->count] = myNode->val[pos];
x2->link[x2->count] = myNode->link[0];
x2->count++;
x2->val[x2->count] = x1->val[j];
x2->link[x2->count] = x1->link[j];
j++;
j = pos;
j++;
myNode->count--;
free(x1);
if (!pos) {
doLeftShift(myNode, 1);
} else {
mergeNodes(myNode, 1);
} else {
if (myNode->count != pos) {
doRightShift(myNode, pos);
} else {
} else {
mergeNodes(myNode, pos);
} else {
doRightShift(myNode, pos);
else
mergeNodes(myNode, pos);
if (myNode) {
pos = 0;
flag = 0;
} else {
if (val == myNode->val[pos]) {
flag = 1;
} else {
flag = 0;
if (flag) {
if (myNode->link[pos - 1]) {
copySuccessor(myNode, pos);
if (flag == 0) {
} else {
removeVal(myNode, pos);
} else {
if (myNode->link[pos]) {
adjustNode(myNode, pos);
return flag;
if (!delValFromNode(val, myNode)) {
return;
} else {
if (myNode->count == 0) {
tmp = myNode;
myNode = myNode->link[0];
free(tmp);
root = myNode;
return;
if (!myNode) {
return;
*pos = 0;
} else {
if (val == myNode->val[*pos]) {
return;
return;
/* B-Tree Traversal */
int i;
if (myNode) {
traversal(myNode->link[i]);
traversal(myNode->link[i]);
int main() {
while (1) {
scanf("%d", &ch);
switch (ch) {
case 1:
scanf("%d", &val);
insertion(val);
break;
case 2:
scanf("%d", &val);
deletion(val, root);
break;
case 3:
scanf("%d", &val);
break;
case 4:
traversal(root);
break;
case 5:
exit(0);
default:
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
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