Anda di halaman 1dari 56

ADVANCED

DATA
STRUCTURES
LAB

1
R 16 Ads lab KISHORE DASARI
1. To perform various operations i.e., insertions and deletions on AVL trees.
#include<stdio.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);

int main()
{
node *root=NULL;
int x,n,i,op;

2
R 16 Ads lab KISHORE DASARI
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;

case 2: printf("\nEnter a data:");


scanf("%d",&x);
root=insert(root,x);

3
R 16 Ads lab KISHORE DASARI
break;

case 3: printf("\nEnter a data:");


scanf("%d",&x);
root=Delete(root,x);
break;

case 4: printf("\nPreorder sequence:\n");


preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);

return 0;
}

node * insert(node *T,int x)


{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;

4
R 16 Ads lab KISHORE DASARI
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}

T->ht=height(T);

return(T);
}

5
R 16 Ads lab KISHORE DASARI
node * Delete(node *T,int x)
{
node *p;

if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);

6
R 16 Ads lab KISHORE DASARI
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;

while(p->left!= NULL)
p=p->left;

T->data=p->data;
T->right=Delete(T->right,p->data);

if(BF(T)==2)//Rebalance during windup


if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}

7
R 16 Ads lab KISHORE DASARI
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

if(lh>rh)
return(lh);

return(rh);
}

node * rotateright(node *x)


{
node *y;
y=x->left;
x->left=y->right;

8
R 16 Ads lab KISHORE DASARI
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);

return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}

node * LL(node *T)


{
T=rotateright(T);

9
R 16 Ads lab KISHORE DASARI
return(T);
}

node * LR(node *T)


{
T->left=rotateleft(T->left);
T=rotateright(T);

return(T);
}

node * RL(node *T)


{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}

int BF(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else

10
R 16 Ads lab KISHORE DASARI
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

void preorder(node *T)


{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}

void inorder(node *T)


{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);

11
R 16 Ads lab KISHORE DASARI
}
}

Output

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:1

Enter no. of elements:4

Enter tree data:7 12 4 9

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:4

12
R 16 Ads lab KISHORE DASARI
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)

Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:3

Enter a data:7

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:4

Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)

13
R 16 Ads lab KISHORE DASARI
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:5

2. To implement operations on binary heap.


i) Vertex insertion
ii) Vertex deletion
iii) Finding vertex
iv) Edge addition and deletion
#include<stdio.h>
#include<stdlib.h>
void insert(int);
void buildheap();
void delete();
void percolatedown(int);
void display();
int a[20],n;
void main()
{
printf("\n\t ___________________________________ ");
printf("\n\t| |");
printf("\n\t| Operations on Binary Heap |");

14
R 16 Ads lab KISHORE DASARI
printf("\n\t1.bulid heap 2.Insert 3.delete 4.Display 5.Exit
printf("\n\t|___________________________________|");
printf("\n\n");
int ch,i,key;

printf("\nEnter the size of heap : ");


scanf("%d",&n);
printf("\nEnter element to insert : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
while(1)
{
printf("\nEnter your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: buildheap();
break;
case 2:printf("Enter the elements to be insert:");
scanf("%d",&key);
insert(key);
break;
case 3: delete();
break;
case 4: display();

15
R 16 Ads lab KISHORE DASARI
break;
case 5: exit (0);
default:printf("\nEnter correct choice !!!\n");
}
}
}
void buildheap()
{
int i;
for(i=n/2;i>=0;i--)
percolatedown(i);
}
void insert(int key)
{
a[n]=key;
n++;
buildheap();
}
void delete()
{
printf("\nDeleted element is %d \n",a[0]);
a[0]=a[n-1];
n--;
percolatedown(0);
}
void display()
{

16
R 16 Ads lab KISHORE DASARI
int i;
printf("\nEntered elements of heap are : \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void percolatedown(int i)
{
int c;
int temp=a[i];
while(2*i+1<n)
{
c=2*i+1;
if(a[c]>a[c+1]&&(c!=n-1))
c=c+1;
if(a[c]<temp)
{
a[i]=a[c];
i=c;
}
else
break;
a[i]=temp;
}
}

17
R 16 Ads lab KISHORE DASARI
18
R 16 Ads lab KISHORE DASARI
3. To implement Prim’s algorithm to generate a min-cost spanning tree
#include<stdio.h>
#include<stdlib.h>

#define infinity 9999


#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;

19
R 16 Ads lab KISHORE DASARI
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;

20
R 16 Ads lab KISHORE DASARI
}

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
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;

21
R 16 Ads lab KISHORE DASARI
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++)

22
R 16 Ads lab KISHORE DASARI
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);
}

Output

Enter no. of vertices:6

Enter the adjacency matrix:


031600
305030
150564
605002
036006
004260

spanning tree matrix:

23
R 16 Ads lab KISHORE DASARI
031000
300030
100004
000002
030000
004200

Total cost of spanning tree=13

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

#include<stdio.h>

#define MAX 30

typedef struct edge


{
int u,v,w;
}edge;

typedef struct edgelist


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

edgelist elist;

24
R 16 Ads lab KISHORE DASARI
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();
}

25
R 16 Ads lab KISHORE DASARI
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);

26
R 16 Ads lab KISHORE DASARI
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()
{

27
R 16 Ads lab KISHORE DASARI
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;
}
printf("\n\nCost of the spanning tree=%d",cost);
}

28
R 16 Ads lab KISHORE DASARI
5. To implement Dijkstra’s algorithm to find shortest path in the graph.
#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");

29
R 16 Ads lab KISHORE DASARI
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);

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];

30
R 16 Ads lab KISHORE DASARI
//initialize pred[],distance[] and visited[]
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;

//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++)

31
R 16 Ads lab KISHORE DASARI
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


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);
}
}

32
R 16 Ads lab KISHORE DASARI
6. To implementation of Static Hashing (Use Linear probing for collision resolution)
#include<stdio.h>
#include<stdlib.h>

/* to store a data (consisting of key and value) in hash table array */


struct item
{
int key;
int value;
};
struct hashtable_item
{
int flag;

33
R 16 Ads lab KISHORE DASARI
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
void init_array()
{
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0;
array[i].data = NULL;
}
}
int hashcode(int key)
{
return (key % max);
}
void insert(int key, int value)
{ int index = hashcode(key);
int i = index;
struct item *new_item = (struct item*) malloc(sizeof(struct item));
new_item->key = key;
new_item->value = value;
while (array[i].flag == 1)
{
if (array[i].data->key == key)

34
R 16 Ads lab KISHORE DASARI
{
printf("\n Key already exists, hence updating its value \n");
array[i].data->value = value;
return;
}
i = (i + 1) % max;
if (i == index)
{
printf("\n Hash table is full, cannot insert any more item \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
size++;
printf("\n Key (%d) has been inserted \n", key);
}
void remove_element(int key)
{
int index = hashcode(key);
int i = index;
while (array[i].flag != 0)
{
if (array[i].flag == 1 && array[i].data->key == key )
{
array[i].flag = 2;
array[i].data = NULL;

35
R 16 Ads lab KISHORE DASARI
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + 1) % max;
if (i == index)
{
break;
}
}
printf("\n This key does not exist \n");
}
void display()
{
int i;
for (i = 0; i < max; i++)
{
struct item *current = (struct item*) array[i].data;
if (current == NULL)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements -: \n %d (key) and %d(value) ", i, current->key, current-
>value);
}
}

36
R 16 Ads lab KISHORE DASARI
}
int size_of_hashtable()
{
return size;
}
void main()
{ int choice, key, value, n, c;
clrscr();
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
init_array();
do {
printf("Implementation of Hash Table in C with Linear Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:

37
R 16 Ads lab KISHORE DASARI
printf("Deleting in Hashtable \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();

Output
Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable

38
R 16 Ads lab KISHORE DASARI
4. Display Hashtable

Please enter your choice-: 3


Size of Hashtable is-: 0

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 1


Inserting element in Hashtable
Enter key and value-: 12 10

Key (12) has been inserted

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

39
R 16 Ads lab KISHORE DASARI
Please enter your choice-: 1
Inserting element in Hash table
Enter key and value-: 122 4

Key (122) has been inserted

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 3


Size of Hashtable is-: 2

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 4


Array[0] has no elements

40
R 16 Ads lab KISHORE DASARI
Array[1] has no elements

Array[2] has elements-:


12 (key) and 10 (value)

Array[3] has elements-:


122(key) and 5(value)

Array[4] has no elements

Array[5] has no elements

Array[6] has no elements

Array[7] has no elements

Array[8] has no elements

Array[9] has no elements

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable

41
R 16 Ads lab KISHORE DASARI
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 2


Deleting in Hashtable
Enter the key to delete-: 122

Key (122) has been removed

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 2


Deleting in Hashtable
Enter the key to delete-: 56

This key does not exist

Do you want to continue-:(press 1 for yes) 2

7. To implement of Huffmann coding.

42
R 16 Ads lab KISHORE DASARI
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 100
struct MinHeapNode {
char data;
unsigned freq;
struct MinHeapNode *left, *right;
};
min heap (or Hufmman tree) nodes
struct MinHeap {
unsigned size;
unsigned capacity;
struct MinHeapNode** array;
};
struct MinHeapNode* newNode(char data, unsigned freq)
{
struct MinHeapNode* temp
= (struct MinHeapNode*)malloc
(sizeof(struct MinHeapNode));
temp->left = temp->right = NULL;
temp->data = data;
temp->freq = freq;
return temp;
}
struct MinHeap* createMinHeap(unsigned capacity)
{
struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));

43
R 16 Ads lab KISHORE DASARI
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array = (struct MinHeapNode**)malloc(minHeap-> capacity * sizeof(struct
MinHeapNode*));
return minHeap;
}
void swapMinHeapNode(struct MinHeapNode** a,
struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < minHeap->size && minHeap->array[left]-> freq < minHeap->array[smallest]-
>freq)
smallest = left;
if (right < minHeap->size && minHeap->array[right]-> freq < minHeap-
>array[smallest]->freq)
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}

44
R 16 Ads lab KISHORE DASARI
}
int isSizeOne(struct MinHeap* minHeap)
{ return (minHeap->size == 1);
}
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)
{
++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {
minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}
void buildMinHeap(struct MinHeap* minHeap)
{ int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);

45
R 16 Ads lab KISHORE DASARI
}
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);
printf("\n");
}
int isLeaf(struct MinHeapNode* root)
{
return !(root->left) && !(root->right);
}
struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size)
{
struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newNode(data[i], freq[i]);
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size)
{
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap)) {
left = extractMin(minHeap);

46
R 16 Ads lab KISHORE DASARI
right = extractMin(minHeap);
top = newNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode* root, int arr[], int top)
{
if (root->left) {
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
if (root->right) {
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
if (isLeaf(root)) {
printf("%c: ", root->data);
printArr(arr, top);
}
}
void HuffmanCodes(char data[], int freq[], int size)
{
struct MinHeapNode* root = buildHuffmanTree(data, freq, size);
int arr[MAX_TREE_HT], top = 0;

47
R 16 Ads lab KISHORE DASARI
printCodes(root, arr, top);
}
int main()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, freq, size);
return 0;
}

Output
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111

8. To implement of B-tree.
#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;

48
R 16 Ads lab KISHORE DASARI
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--;
}
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--;
}
/* sets the value val in the node */
int setValueInNode(int val, int *pval,
struct btreeNode *node, struct btreeNode **child) {

49
R 16 Ads lab KISHORE DASARI
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;
}
/* 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) {

50
R 16 Ads lab KISHORE DASARI
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];
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;
}
/* 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++;

51
R 16 Ads lab KISHORE DASARI
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);
}
} 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) {

52
R 16 Ads lab KISHORE DASARI
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--);
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)) {
printf("Given value is not present in B-Tree\n");
return;
} else {
if (myNode->count == 0) {
tmp = myNode;
myNode = myNode->link[0];
free(tmp);
}

53
R 16 Ads lab KISHORE DASARI
}
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;
}
/* 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);

54
R 16 Ads lab KISHORE DASARI
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &val);
deletion(val, root);
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");
}
}

Output

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
Enter your input:67

55
R 16 Ads lab KISHORE DASARI
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

56
R 16 Ads lab KISHORE DASARI

Anda mungkin juga menyukai