+ All Categories
Home > Documents > ADS R10 LAB MANUAL IN C

ADS R10 LAB MANUAL IN C

Date post: 29-Oct-2015
Category:
Upload: corey-lewis
View: 234 times
Download: 1 times
Share this document with a friend
Description:
Max programs are covered
119
ADVANCED DATASTRUCTURES LAB MANUAL EXERCISE-1: AIM: To implement functions of Dictionary using Hashing (Division method, Multiplication method) DESCRIPTION:- Dictionary is a collection of data elements uniquely identified by a field called key. A dictionary supports the operations of search,insert and delete. A dictionary supports both sequential and random access. These are useful in implementing symbol tables,text retrieval systems,data base systems,etc. Hash tables: “Hash table” is a data structure in which keys are mapped to array positions by a hash function. Hash function: A “Hash function” is simply a mathematical formula which when applied to a key,produce an integer which can be used as an index for the key in the hash table. Hashing:The process of mapping the keys to appropriate locations(or indexes) in a hash table is called “Hashing” There are different types of hash functions to calculate the hash value.They are 1.Division method 2.Multiplication method 5.Universal hashing Division method: BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 1
Transcript
Page 1: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

EXERCISE-1:

AIM: To implement functions of Dictionary using Hashing (Division method,

Multiplication method)

DESCRIPTION:-

Dictionary is a collection of data elements uniquely identified by a field called key.

A dictionary supports the operations of search,insert and delete.

A dictionary supports both sequential and random access.

These are useful in implementing symbol tables,text retrieval

systems,data base systems,etc.

Hash tables: “Hash table” is a data structure in which keys are mapped to array positions by

a hash function.

Hash function: A “Hash function” is simply a mathematical formula which when applied to

a key,produce an integer which can be used as an index for the key in the hash table.

Hashing:The process of mapping the keys to appropriate locations(or indexes) in a hash

table is called “Hashing”

There are different types of hash functions to calculate the hash value.They are

1.Division method

2.Multiplication method

5.Universal hashing

Division method:

It is the most simple method of hashing an integer x.This method divides x by M and then

uses the remainder that is obtained.The hash function can be given as

H(z)=z mod M

The division method is good for any value of M because it requires only a single division

method or operation .It works very fast.But care must be taken to select a suitable value for

M.

Generally it is best to choose M to be a prime number .

And M should also be not too close to the exact powers of 2.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 1

Page 2: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Code:

int const M=97; //prime value

int h(int x)

{

return(x%M);

}

Example:

calculate the hash values of keys 1234 and 5462 assume M=97.

h(1234)=1234%97=70

h(5462)=5462%97=16

Multiplication method:

The steps involved in multiplication method are as follows:

Step1: Choose a constant R such that 0<A<1.

Step2: Multiply the key K by A.

Step3: Extract the fractional part of KA.

Step4: Multiply the result of step3 by M and take the floor.

Hence the hash function can be given as

h(x)=[m(KA mod 1)]

where (KA mod 1) gives the fractional part of KA and M is the total number of indices in the

hash table.The greatest advantage of this method is that it works with any value of A. The

best choice of A is (sqrt-1)/2=0.61803398.

Example: Given a hash table of size 1000,map the key 12345 to an appropriate location in

the hash table.

Sol: We will use A=0.618033,m=1000,k=12345

h(12345)=[1000(12345*0.618033)]

=[1000(7629.617385 mod 1)]

=[1000(0.617385)]

=[617.385]

=617

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 2

Page 3: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM:

/*implement functions of Dictionary using Hashing ( Division method)*/

#include<stdio.h>

#include<conio.h>

#include<math.h>

#define MAX 10

struct DCT

{

int k;

int val;

}a[MAX];

voidDicHash();

int hash(int);

void insert(int,int,int);

void display();

void size();

void search(int);

void DicHash()

{

int i;

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

a[i].k=a[i].val=-1;

}

int hash(int num)

{

int hkey;

hkey=num%10;

return hkey;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 3

Page 4: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

void display()

{

int i;

printf("Hash Table is\n ");

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

printf("%d\t%d\t%d\n",i,a[i].k,a[i].val);

}

void insert(int index,int key,int value)

{

int flag=0,i,count=0;

if(a[index].k==-1)

{

a[index].k=key;

a[index].val=value;

}

else

{

i=0;

while(i<MAX)

{

if(a[i].k != -1)

count++;

i++;

}

if(count==MAX)

{

printf("Hash Table is Full ");

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 4

Page 5: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

return;

}

for(i=index+1;i<MAX;i++)

if(a[i].k==-1)

{

a[i].k=key;

a[i].val=value;

flag=1;

break;

}

for(i=0;i<index&&flag==0;i++)

if(a[i].k==-1)

{

a[i].k=key;

a[i].val=value;

flag=1;

break;

}

}

}

void size()

{

int i,len=0;

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

if(a[i].k != -1)

len++;

printf("size of the Dictionary is len %d",len);

}

void search(int search_key)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 5

Page 6: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

int i,j;

i=hash(search_key);

if(a[i].k==search_key)

{

printf("The record is present at location %d\n",i);

return ;

}

if(a[i].k!=search_key)

{

for(j=i+1;j<MAX;j++)

{

if (a[j].k==search_key)

{

printf("The record is present at location %d\n" ,j);

return;

}

}

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

if (a[j].k==search_key)

{

printf("The record is present at location %d\n",j);

return;

}

printf("The record not found\n");

}

else

printf("The record is not present in the hash table\n");

}

void main()

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 6

Page 7: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

int ch;

int hkey,key,value;

clrscr();

DicHash();

do

{

printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice");

scanf("%d",&ch);

switch(ch)

{

case 1:printf("enter key and value:");

scanf("%d%d",&key,&value);

hkey=hash(key);

insert(hkey,key,value);

break;

case 2:printf("enter key ");

scanf("%d",&key);

search(key);

break;

case 3:display();

break;

case 4:size();

break;

}

}while(ch!=5);

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 7

Page 8: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

EXPECTED OUTPUT:

1.insert

2.search

3.Display

4.size

5.exit

Enter your choice: 1

Enter key and value: 12 13

Enter your choice: 1

Enter key and value: 14 29

Enter your choice: 3

Hash table is:Index key value 0 -1 -1 1 -1 -1 2 12 13 3 -1 -1 4 14 29 5 -1 -1 6 -1 -1 7 -1 -1 8 -1 -1 9 -1 -1 10 -1 -1

Enter your choice: 2

Enter key: 14

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 8

Page 9: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

The record is present at location 4.

Enter your choice: 4 Size of dictionary is : 3

/*implement functions of Dictionary using Hashing ( Multiplication method)*/

#include<stdio.h>

#include<conio.h>

#include<math.h>

#define MAX 200

struct DCT

{

int k;

int val;

}a[MAX];

voidDicHash();

int hash(int);

void insert(int,int,int);

void display();

void size();

void search(int);

void DicHash()

{

int i;

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

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 9

Page 10: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

a[i].k=a[i].val=-1;

}

int hash(int key)

{

int hkey;

float A=0.618;

hkey=floor(2*(key*A));

return hkey;

}

void display()

{

int i;

printf("Hash Table is\n ");

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

{

if(a[i].k!=-1)

printf("%d\t%d\t%d\n",i,a[i].k,a[i].val);

}

}

void insert(int index,int key,int value)

{

int flag=0,i,count=0;

if(a[index].k==-1)

{

a[index].k=key;

a[index].val=value;

}

else

{

i=0;

while(i<MAX)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 10

Page 11: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

if(a[i].k != -1)

count++;

i++;

}

if(count==MAX)

{

printf("Hash Table is Full ");

return;

}

for(i=index+1;i<MAX;i++)

if(a[i].k==-1)

{

a[i].k=key;

a[i].val=value;

flag=1;

break;

}

for(i=0;i<index&&flag==0;i++)

if(a[i].k==-1)

{

a[i].k=key;

a[i].val=value;

flag=1;

break;

}

}

}

void size()

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 11

Page 12: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

int i,len=0;

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

if(a[i].k != -1)

len++;

printf("size of the Dictionary is len %d",len);

}

void search(int search_key)

{

int i,j;

i=hash(search_key);

if(a[i].k==search_key)

{

printf("The record is present at location %d\n",i);

return ;

}

if(a[i].k!=search_key)

{

for(j=i+1;j<MAX;j++)

{

if (a[j].k==search_key)

{

printf("The record is present at location %d\n" ,j);

return;

}

}

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

if (a[j].k==search_key)

{

printf("The record is present at location %d\n",j);

return;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 12

Page 13: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

printf("The record not found\n");

}

else

printf("The record is not present in the hash table\n");

}

void main()

{

int ch;

int hkey,key,value;

clrscr();

DicHash();

do

{

printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice");

scanf("%d",&ch);

switch(ch)

{

case 1:printf("enter key and value:");

scanf("%d%d",&key,&value);

hkey=hash(key);

insert(hkey,key,value);

break;

case 2:printf("enter key ");

scanf("%d",&key);

search(key);

break;

case 3:display();

break;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 13

Page 14: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

case 4:size();

break;

}

}while(ch!=5);

EXPECTED OUTPUT:

1.Insert

2.search

3.display

4.size

5.exit

Enter your choice: 1

Enter key and value: 23 456

Enter your choice:1

Enter key and value: 12 359

Enter your choice: 3

Hash table is

14 12 359

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 14

Page 15: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

28 23 456

Enter your choice: 2

Enter key: 12

The record is present at location : 14

Enter your choice : 4

Size of the dictionary is : 2

Enter your choice: 5

EXERCISE2:

AIM: To perform various operations i.e, insertions and deletions on AVL tree

DESCRIPTION: AVL tree is a self-balancing Binary Search Tree (BST) where the difference

between heights of left and right subtrees cannot be more than one for all nodes.

INSERTION:

To make sure that the given tree remains AVL after every insertion, we must augment the

standard BST insert operation to perform some re-balancing. Following are two basic

operations that can be performed to re-balance a BST without violating the BST property

(keys(left)<key(root)<keys(right)).

1)LeftRotation

2)Right Rotation

T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side) y x / \ Right Rotation / \ x T3 – - – - – - – > T1 y / \ < - - - - - - - / \ T1 T2 Left Rotation T2 T3Keys in both of the above trees follow the following order

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 15

Page 16: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)So BST property is not violated anywhere.

STEPS TO FOLLOW FOR INSERTION

Let the newly inserted node be w

step1) Perform standard BST insert for w.

step2) Starting from w, travel up and find the first unbalanced node.

Let z be the first unbalanced node, y be the child of z that comes on the path from w

to z and x be the grandchild of z that comes on the path from w to z.

step3) Rebalance the tree by performing appropriate rotations on the subtree rooted with z

There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4

ways. Following are the possible 4 arrangements:

a) y is left child of z and x is left child of y (Left Left Case)

b) y is left child of z and x is right child of y (Left Right Case)

c) y is right child of z and x is right child of y (Right Right Case)

d) y is right child of z and x is left child of y (Right Left Case)

a) Left Left Case

T1, T2, T3 and T4 are subtrees. z y / \ / \ y T4 Right Rotate (z) x z / \ - - - - - - - - -> / \ / \ x T3 T1 T2 T3 T4 / \ T1 T2

b) Left Right Case

z z x / \ / \ / \ y T4 Left Rotate (y) x T4 Right Rotate(z) y z / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \T1 x y T3 T1 T2 T3 T4 / \ / \ T2 T3 T1 T2

c) Right Right Case

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 16

Page 17: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

z y / \ / \ T1 y Left Rotate(z) z x / \ - - - - - - - -> / \ / \ T2 x T1 T2 T3 T4 / \ T3 T4

d) Right Left Case

z z x / \ / \ / \ T1 y Right Rotate (y) T1 x Left Rotate(z) z x / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ x T4 T2 y T1 T2 T3 T4 / \ / \T2 T3 T3 T4

DELETION:

To make sure that the given tree remains AVL after every deletion, we must augment the

standard BST delete operation to perform some re-balancing. Following are two basic

operations that can be performed to re-balance a BST without violating the BST property

(keys(left)<key(root)<keys(right)).

1)LeftRotation

2) Right Rotation

STEPS TO FOLLOW FOR DELETION:

Step1: Perform the normal BST deletion

Step2: The current node must be one of the ancestors of the deleted node.Update the

height of the current node.

Step3:Get the balance factor of the current node

Step4:If balance factor is greater than 1,then the current node is unballenced and we are

either in left left case or left right case. To check whether it is Left Left case or Left Right

case, get the balance factor of left subtree.If balance factor of the left subtree is greater

than or equal to 0, then it is Left Left case, else Left Right case.

Step5: If balance factor is less than -1, then the current node is unbalanced and we are

either in Right Right case or Right Left case. To check whether it is Right Right case or Right

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 17

Page 18: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Left case, get the balance factor of right subtree. If the balance factor of the right subtree is

smaller than or equal to 0, then it is Right Right case, else Right Left case.

SAMPLE PROGRAM:

/*C Program to insert and delete elements in an AVL Tree*/#include<stdio.h>

#include<conio.h>

#include<alloc.h>

#define FALSE 0

#define TRUE 1

struct AVLNode

{

int data;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 18

Page 19: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

int balfact;

struct AVLNode *left;

struct AVLNode *right;

};

struct AVLNode * avlinsert(struct AVLNode *,int,int *);

struct AVLNode * avldelete(struct AVLNode *,int,int *);

struct AVLNode * del(struct AVLNode *,struct AVLNode *,int *);

struct AVLNode * balr(struct AVLNode *,int *);

struct AVLNode * ball(struct AVLNode *,int *);

void display(struct AVLNode *);

struct AVLNode * deltree(struct AVLNode *);

int h;

void main()

{

int ch,item;

struct AVLNode *avl=NULL;

clrscr();

do

{

printf("\n1.insert ...\n2.Deletion of an item...\n 3.Deletion of an avltree....\n 4.display

5.exit\n");

printf("Enter ur choice:");

scanf("%d",&ch);

switch(ch)

{

case 1:printf("Enter item to be inserted in the avl tree:");

scanf("%d",&item);

avl=avlinsert(avl,item,&h);

break;

case 2:printf("Enter item to be deleted from the avl tree:");

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 19

Page 20: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

scanf("%d",&item);

avl=avldelete(avl,item,&h);

break;

case 3:avl=deltree(avl);

case 4:display(avl);

break;

}

}while(ch!=5);

}

/* Inserts an element intp tree */

struct AVLNode * avlinsert(struct AVLNode *root,int data,int *h)

{

struct AVLNode *node1,*node2;

if(!root)

{

root=(struct AVLNode *)malloc(sizeof(struct AVLNode));

root->data=data;

root->left=NULL;

root->right=NULL;

root->balfact=0;

*h=TRUE;

return(root);

}

if(data < root->data)

{

root->left=avlinsert(root->left,data,h);

/* If left subtree is higher */

if(*h)

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 20

Page 21: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

switch(root->balfact)

{

case 1:

node1=root->left;

if(node1->balfact==1)

{

printf("\n Right Rotation alond %d. ",root->data);

root->left=node1->right;

node1->right=root;

root->balfact=0;

root=node1;

}

else

{

printf("\n Double rotation , left along %d",node1->data);

node2=node1->right;

node1->right=node2->left;

printf(" then right along %d. \n",root->data);

node2->left=node1;

root->left=node2->right;

node2->right=root;

if(node2->balfact==1)

root->balfact=-1;

else

root->balfact=0;

if(node2->balfact==-1)

node1->balfact=1;

else

node1->balfact=0;

root=node2;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 21

Page 22: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

root->balfact=0;

*h=FALSE;

break;

case 0:

root->balfact=1;

break;

case -1:

root->balfact=0;

*h=FALSE;

}

}

}

if(data > root->data)

{

root->right=avlinsert(root->right,data,h);

/* If the right subtree is higher */

if(*h)

{

switch(root->balfact)

{

case 1:

root->balfact=0;

*h=FALSE;

break;

case 0:

root->balfact=-1;

break;

case -1:

node1=root->right;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 22

Page 23: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

if(node1->balfact==-1)

{

printf("\n Left rotation along %d. ",root->data);

root->right=node1->left;

node1->left=root;

root->balfact=0;

root=node1;

}

else

{

printf("\n Double rotation , right along %d",node1->data);

node2=node1->left;

node1->left=node2->right;

node2->right=node1;

printf(" then left along %d. \n",root->data);

root->right=node2->left;

node2->left=root;

If(node2->balfact==-1)

root->balfact=1;

else

root->balfact=0;

if(node2->balfact==1)

node1->balfact=-1;

else

node1->balfact=0;

root=node2;

}

root->balfact=0;

*h=FALSE;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 23

Page 24: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

}

}

return(root);

}

/* Deletes an item from the tree */

struct AVLNode * avldelete(struct AVLNode *root,int data,int *h)

{

struct AVLNode *node,*tp;

node=root;/*if there is only one node*/

if((root)&&(node->left==NULL)&&(node->right==NULL))

{

*h=TRUE;

free(node);

root=NULL;

return (root);

}

if(!root)

{

printf("\n No such data. ");

return (root);

}

else

{

if(data < root->data)

{

root->left=avldelete(root->left,data,h);

if(*h)

root=balr(root,h);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 24

Page 25: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

else

{

if(data > root->data)

{

root->right=avldelete(root->right,data,h);

if(*h)

root=ball(root,h);

}

else

{

node=root;

if((node->right==NULL)&&(node->data==data))

{

tp=node;

root=node->left;

printf("new:%d",root->data);

getch();

tp->left=NULL;

free(tp);

*h=TRUE;

return(root);

}

else

{

if(node->left==NULL)

{

root=node->right;

*h=TRUE;

free(node);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 25

Page 26: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

else

{

node->right=del(node->right,node,h);

if(*h)

root=ball(root,h);

}

}

}

}

}

return(root); }

struct AVLNode * del(struct AVLNode *succ,struct AVLNode *node,int *h)

{

struct AVLNode *temp=succ;

if(succ->left!=NULL)

{

succ->left=del(succ->left,node,h);

if(*h)

succ=balr(succ,h);

}

else

{

temp=succ;

node->data=succ->data;

succ=succ->right;

free(temp);

*h=TRUE;

}

return(succ);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 26

Page 27: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

/* Balance the tree , if right subtree is higher */

struct AVLNode * balr(struct AVLNode *root,int *h)

{

struct AVLNode *node1,*node2;

switch(root->balfact)

{

case 1:

root->balfact=0;

break;

case 0:

root->balfact=-1;

*h=FALSE;

break;

case -1:

node1=root->right;

if(node1->balfact <= 0)

{

printf("\n Left rotation along %d. ",root->data);

root->right=node1->left;

node1->left=root;

if(node1->balfact==0)

{

root->balfact=-1;

node1->balfact=1;

*h=FALSE;

}

else

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 27

Page 28: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

root->balfact=node1->balfact=0;

}

root=node1;

}

else

{

printf("\n Double rotation , right along %d ",node1->data);

node2=node1->left;

node1->left=node2->right;

node2->right=node1;

printf(" then left along %d. \n",root->data);

root->right=node2->left;

node2->left=root;

if(node2->balfact==-1)

root->balfact=1;

else

root->balfact=0;

if(node2->balfact==1)

node1->balfact=-1;

else

node1->balfact=0;

root=node2;

node2->balfact=0;

}

}

return (root);

}

/* Balances the tree , if the left subtree is higher */

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 28

Page 29: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

struct AVLNode * ball(struct AVLNode * root,int *h)

{

struct AVLNode *node1,*node2;

switch(root->balfact)

{

case -1:

root->balfact=0;

break;

case 0:

root->balfact=1;

*h=FALSE;

break;

case 1:

node1=root->left;

if(node1->balfact >= 0)

{

printf("]n Right rotation along %d. ",root->data);

root->left=node1->right;

node1->right=root;

if(node1->balfact==0)

{

root->balfact=1;

node1->balfact=-1;

*h=FALSE;

}

else

{

root->balfact=node1->balfact=0;

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 29

Page 30: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

root=node1;

}

else

{

printf("\n Double rotation , left along %d ",node1->data);

node2=node1->right;

node1->right=node2->left;

node2->left=node1;

printf(" then right along %d .\n",root->data);

root->left=node2->right;

node2->right=root;

if(node2->balfact==1)

root->balfact=-1;

else

root->balfact=0;

if(node2->balfact==-1)

node1->balfact=1;

else

node1->balfact=0;

root=node2;

node2->balfact=0;

}

}

return (root);

}

/*n Displays the tree in-order */

void display(struct AVLNode *root)

{

if(root!=NULL)

{

display(root->left);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 30

Page 31: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf("%d\t",root->data);

display(root->right);

}

}

/* Deletes the tree */

struct AVLNode *deltree(struct AVLNode * root)

{

int h;

root->left=NULL;

root->right=NULL;

free(root);

root=NULL;

return(root);

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 31

Page 32: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

EXPECTED OUTPUT:

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:23

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:12

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 32

Page 33: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

12 23 45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:18

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:22

Left Rotation along 12

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4

12 18 22 23 45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 33

Page 34: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Enter an element to be inserted in the AVL Tree:17

Right Rotation along 23

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4

12 17 18 22 23 45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:2

Enter element to be deleted:17

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4

12 18 22 23 45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:1

Enter an element to be inserted in the AVL Tree:40

Left Rotation along 18

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 34

Page 35: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4

12 18 22 23 40 45

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:2

Enter Element to be deleted from the AVL Tree:23

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:2

Enter Element to be deleted from the AVL Tree:18

1.INSERT…

2.DELETE AN ITEM…

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:2

Enter Element to be deleted from the AVL Tree:40

Right Rotation along 45

1.INSERT…

2.DELETE AN ITEM…

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 35

Page 36: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

3.DELETION OF AN AVL TREE

4.DISPLAY

5.EXIT

ENTER UR CHOICE:4 12 22 45

EXERCISE:4

AIM:To implement operations on Binary heap

DESCRIPTION:

Binary Heap: A binary heap is defined as a complete binary tree with elements at every

node being either less than or equal to the element at its left and the right child.

MAX HEAP:The elements at every node will either be less than or equal to the element at its

left and right child

MIN HEAP:The elements at every node will either be greater than or equal to the element

at its left and right child.

There are two types of operations that are performed in Binary heap

Insertion in a binary heap

Deleting an element from a binary heap

INSERT AN ELEMENT:In binary heap elements can be added randomly.

ALGORITHM FOR INSERTION:

Step1:Add the new value and set its pos SET N=N+1,POS=N

Step2:SET HEAP[N]=VAL;

Step3:Find appropriate location of VAL .Repeat steps 4,5 while POS<0

Step4:SET PAR=POS/2;

Step5:if HEAP[POS]<=HEAP[PAR],then goto step6

Else swap HEAP[POS],HEAP[PAR]

POS=PAR

Step6:return

DELETE AN ELEMENT:In binary heap only the element with the higest value is removed in

case of MAX HEAP,and the element with the minimum value is removed in case of MINHEAP

ALGORITHM FOR DELETION:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 36

Page 37: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Step1: [Remove the last node from the heap]

SET LAST=HEAP[N],SET N=N-1

Step2: [Initialize]SET PTR=0,LEFT=1,RIGHT=2

Step3: SET HEAP[PTR]=LAST

Step4: Repeat steps 5 to 7 while LEFT<=N

Step5: if HEAP[PTR]>=HEAP[LEFT] & HEAP[PTR]>=HEAP[RIGHT],then goto step 8.

Step6: if HEAP[RIGHT]<=HEAP[LEFT] then Swap HEAP[PTR],HEAP[LEFT]

SET PTR=LEFT

Else

Swap HEAP[PTR],HEAP[RIGHT]

SET PTR=RIGHT

Step7: SET LEFT=2*PTR & RIGHT=LEFT+1

Step8: return

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 37

Page 38: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM:

/* Program to implement Binary heap operations */

#include<stdio.h>

#include<conio.h>

struct heap

{

int h[50];

int hsize;

}he;

void create();

void insert();

int delete();

void size();

void display();

void size()

{

he.hsize=0;

}

void create()

{

Int i,root,ch;

int p;

printf("\n Enter Heap size: \n");

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 38

Page 39: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

scanf("%d",&he.hsize);

printf("\n Enter Elements of Heap : \n");

for(i=1;i<=he.hsize;i++)

{

scanf("%d",&he.h[i]);

}

for(root=he.hsize/2;root>=1;root--)

{

p=he.h[root];

ch=root*2;

while(ch<=he.hsize)

{

if(ch<he.hsize&&he.h[ch+1]>he.h[ch])

ch++;

if(p>he.h[ch])

break;

he.h[ch/2]=he.h[ch];

ch=ch*2;

}

he.h[ch/2]=p;

}

}

void display()

{

int i;

if(he.hsize==0)

printf("heap empty\n");

else

{

printf("\n\n HEAP ELEMENTS \n\n");

for(i=1;i<=he.hsize;i++)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 39

Page 40: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf("%d\t",he.h[i]);

}

}

void insert()

{

int el;

int cn;

printf("\n Enter Element: \n");

scanf("%d",&el);

he.hsize++;

cn=he.hsize;

while(cn!=1 && he.h[cn/2]<el)

{

he.h[cn]=he.h[cn/2];

cn=cn/2;

}

he.h[cn]=el;

}

int delete()

{

int i,ch,el,le;

if(he.hsize==0)

{

printf("\n heap empty. \n");

return(0);

}

else

{

el=he.h[1];

le=he.h[he.hsize];

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 40

Page 41: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

he.hsize--;

ch=2;

while(ch<=he.hsize)

{

if(ch<he.hsize &&he.h[ch+1]>he.h[ch])

ch++;

if(le>he.h[ch])

break;

he.h[ch/2]=he.h[ch];

ch=ch*2;

}

he.h[ch/2]=le;

return(el);

}

}

void main()

{

int x,opt,i;

size();

do

{

printf(”\n BINARY HEAP OPERATIONS”);

printf("\n1.Create \n2.Insert \n3.DELETE \n4.Display \n5.Exit");

printf("\n Enter Option \n");

scanf("%d",&opt);

switch(opt)

{

case 1: create();

break;

case 2: insert();

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 41

Page 42: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

break;

case 3: x=delete();

if(x!=0)

printf("\n Deleted Element : \t %d",x);

break;

case 4:display();

break;

case 5:break; }

}while(opt!=5);

getch(); }

EXPECTED OUTPUT:

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:1

Enter Heap Size:5

Enter Elements of Heap:12 45 23 86 56

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:4

Heap Elements: 86 56 23 12 45

BINARY HEAP OPERATIONS

1.Create

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 42

Page 43: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

2.Insert

3.Delete

4.Display

5.Exit

Enter option:2

Enter Element: 28

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:4

Heap Elements: 86 56 28 12 45 23

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:3

Deleted Element:86

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:4

Heap Elements : 56 45 28 12 23

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 43

Page 44: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

BINARY HEAP OPERATIONS

1.Create

2.Insert

3.Delete

4.Display

5.Exit

Enter option:5

EXERCISE-5:

AIM: To implement operations on graphs

DESCRIPTION:

GRAPH: A graph is a collection of nodes called vertices and a collection of segments called

lines,connecting parts of vertices Graphs may be Directed or Un-Directed.

OPERATIONS ON GRAPHS:

There are several primitive graph operations that provide the basic modules needed

to maintain a graph.

1. Insert a vertex.

2. Delete a vertex

3. Find a vertex.

4. Insert an edge.

5. Delete an edge.

6. Find edge.

1.INSERT A VERTEX:- Insert vertex adds a new vertex to a graph.When a vertex is inserted,it

is disjoint,That is,it is not connected to any other vertices is just the first step in the insertion

process. After a vertex is inserted,it must be connected.

Algorithm for Insert Vertex: It allocates memory for a new vertex and copies the` data to it.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 44

Page 45: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Input:Graph is a reference to graph head structure datain contains data to be inserted into

vertex.

Output: New vertex allocated and data copied.

Algorithm insertvertex(graph,datain) :

Step1: Allocate memory for new vertex.

Step2: Store datain in new vertex.

Step3: Initialize metadata elements in newnode.

Step4: Increment graph count.

Step5: if(graph is empty)

5.1 Set graph first to newnode.

STEP : 6 else

6.1 Search for insertion point

6.2 If(inserting before first vertex

Set graph first to new vertex.

6.3 else insert new vertex in sequence.

end insert vetex.

2.DELETE VERTEX: Delete vertex removes a vertex from the graph when a vertex is

deleted,all connecting edges are also removed.The first thing we have to do to delete a

vertex is find it. Once we have found it, however we also need to make sure that it is

disjoint,that is we need to ensure that there are no arcs leaving (or) entering the vertex.

Algorithm for Delete Vertex:- It deletes an existing vertex only if its degree os “0”.

Input: Graph is a reference pointer to graph head key is the key of the vertex to be deleted.

Output: Vertex deleted(if degree zero)

Return:

+1 if successful

-1 if degree not zero

-2 if key not found

Algorithm delete vertex(graph,key)

STEP : 1 if(empty graph)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 45

Page 46: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

1.1 return -2

STEP : 2 Search for vertex to be deleted.

STEP : 3 If vertex not found

3.1 return -2

STEP : 4 Test degree of the vertex

If(vertex indegree>0 OR outdegree>0)

4.1 return -1

STEP : 5 Delete vertex

STEP : 6 Decrement graph count

STEP : 7 return 1

End delete vertex.

3.FIND VERTEX:-Find vertex traverses a graph, looking for a special vertex. If the vertex is

found its data are returned. If it is not found, an error is indicated.

Algorithm to Find Vertex:-

Input : Graph is reference to a graph head structure key is the key of the vertex data.

Dataout is reference to data variable.

Output Vertex data copied to dataout.

Return:

+1 isf successful

-2 if key not found

Algorithm retrieve vertex(graph,key,dataout)

STEP : 1 If graph is empty return -2

STEP : 2 Search for vertex

STEP : 3 if vertex found

3.1 move location pointer data to dataout

Return 1

STEP : 4 otherwise return -2

End find vertex.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 46

Page 47: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

4.INSERT EDGE:- Add edge connects a vertex to a destination vertex. Two vertices must be

specified, to add an edge. If the graph is a digraph, one of the vertices must be specified as

the source and the other one as the destination. If a vertex tequires multiple edges, add an

edge must be called once for each adjacent vertex.Insert arc (or) edge requires two points in

the graph. The source vertex (fromptr) and the destination vertex(toptr).Each vertex is

identified by its key value rather than by its physical address.

Algorithm for Insert Edge:

Input: Graph is reference to graph head structure fromkey is the key of the source vertex to

key is the key of destination vertex.

Output: Arc added to adjacency list.

Return:

+1 if successful

-2 if fromkey not found

-3 if tokey not found

Algorithm insertArc(graph,fromkey,tokey)

STEP : 1 Allocate memory for new arc

STEP : 2 Search and set fromvertex.

STEP : 3 if(from vertex not found)

Return -2

STEP : 4 Search and set tovertex

STEP : 5 if(tovetex not found)

Return -3

STEP : 6 From and to vertices located, Insert new arc

STEP : 7 Increment fromvertex outdegree

STEP : 8 Increment tovertex indegreee

STEP : 9 Set arc destination to tovertex

STEP : 10 if(fromvertex arc list empty)

10.1 Set fromvertex first arc to new arc

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 47

Page 48: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

10.2 Set new arc next arc to null

10.3 return 1

STEP : 11 Find insertion point in the arc list.

STEP : 12 if(insert at beginning of arc list)

12.1 Insertion before first arc i.e set fromvertex

First arc to new arc

STEP : 13 Insert in arc list

STEP : 14 return 1

End insertArc

4.DELETE EDGE: Delete edge removes one edge from a graph.to identify an arc, we need

two vertices. The vertices are identified by their key. The algorithm therefore first searches

the vertex list for the start vertex and searches the vertex list for the start vertex and

searches its adjacency list for the destination vertex. After locating and deleting arc, the

dergree in the form and to vertices is adjusted and the memory recycled.

Algorithm for Delete Edge:

Input:Graph is reference to a graph head structure fromkey is the key of the source vertex

tokey is the key of destination vertex

Output: Vertex deleted.

Return:

+1 if successful

-2 if fromkey not found

-3 if tokey not found

STEP 1 : if(empty graph)

Return -2

STEP : 2 Search and set fromvertex to vertex with key equal to fromkey.

STEP : 3 if(fromvertex not found)

Return -2

STEP : 4 if(fromvertex arc list null) then

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 48

Page 49: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Return -3

STEP : 5 Search and find arc with key equql to tokey

STEP : 6 if(tokey not found) then

Return -3

STEP : 7 7.1 Set tovertex to arc destination

7.2 delete arc

7.3 decrement fromvertex outdegree

7.4 decrement tovertex indegree

7.5 return

End deleteArc

SAMPLE PROGRAM:

#include<stdio.h>

struct node

{

struct node *next;

char name;

struct edge *adj;

}*start = NULL;

struct edge

{

char dest;

struct edge *link;

};

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 49

Page 50: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

struct node *find( char item );

main()

{

int choice;

char node, origin, destin;

while ( 1 )

{

printf(“\n GRAPH OPERATIONS \t ”);

printf( "1.Insert a node\n" );

printf( "2.Insert an edge\n" );

printf( "3.Delete a node\n" );

printf( "4.Delete an edge\n" );

printf( "5.Display\n" );

printf( "6.Exit\n" );

printf( "Enter your choice : " );

scanf( "%d", &choice );

switch ( choice )

{

case 1:printf( "Enter a node to be inserted : " );

fflush( stdin );

scanf( "%c", &node );

insert_node( node );

break;

case 2: printf( "Enter an edge to be inserted : " );

fflush( stdin );

scanf( "%c %c", &origin, &destin );

insert_edge( origin, destin );

break;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 50

Page 51: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

case 3:printf( "Enter a node to be deleted : " );

fflush( stdin );

scanf( "%c", &node );

/*This fn deletes the node from header node list*/

delete_node( node );

/* This fn deletes all edges coming to this node */

delnode_edge( node );

break;

case 4:printf( "Enter an edge to be deleted : " );

fflush( stdin );

scanf( "%c %c", &origin, &destin );

del_edge( origin, destin );

break;

case 5:display();

break;

case 6:exit();

default:printf( "Wrong choice\n" );

break;

} /*End of switch*/

} /*End of while*/

} /*End of main()*/

insert_node( char node_name )

{

struct node * tmp, *ptr;

tmp = malloc( sizeof( struct node ) );

tmp->name = node_name;

tmp->next = NULL;

tmp->adj = NULL;

if ( start == NULL )

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 51

Page 52: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

start = tmp;

return ;

}

ptr = start;

while ( ptr->next != NULL )

ptr = ptr->next;

ptr->next = tmp;

} /*End of insert_node()*/

delete_node( char u )

{

struct node * tmp, *q;

if ( start->name == u )

{

tmp = start;

start = start->next; /* first element deleted */

free( tmp );

return ;

}

q = start;

while ( q->next->next != NULL )

{

if ( q->next->name == u ) /* element deleted in between */

{

tmp = q->next;

q->next = tmp->next;

free( tmp );

return ;

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 52

Page 53: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

q = q->next;

} /*End of while*/

if ( q->next->name == u ) /* last element deleted */

{

tmp = q->next;

free( tmp );

q->next = NULL;

}

} /*End of delete_node()*/

delnode_edge( char u )

{

struct node * ptr;

struct edge *q, *start_edge, *tmp;

ptr = start;

while ( ptr != NULL )

{

/* ptr->adj points to first node of edge linked list */

if ( ptr->adj->dest == u )

{

tmp = ptr->adj;

ptr->adj = ptr->adj->link; /* first element deleted */

free( tmp );

continue; /* continue searching in another edge lists */

}

q = ptr->adj;

while ( q->link->link != NULL )

{

if ( q->link->dest == u )/* element deleted in between */

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 53

Page 54: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

tmp = q->link;

q->link = tmp->link;

free( tmp );

continue;

}

q = q->link;

} /*End of while*/

if ( q->link->dest == u ) /* last element deleted */

{

tmp = q->link;

free( tmp );

q->link = NULL;}

ptr = ptr->next;

} /*End of while*/

} /*End of delnode_edge()*/

insert_edge( char u, char v )

{

struct node * locu, *locv;

struct edge *ptr, *tmp;

locu = find( u );

locv = find( v );

if ( locu == NULL )

{

printf( "Source node not present ,first insert node %c\n", u );

return ;

}

if ( locv == NULL )

{

printf( "Destination node not present ,first insert node %c\n", v );

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 54

Page 55: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

return ;

}

tmp = malloc( sizeof( struct edge ) );

tmp->dest = v;

tmp->link = NULL;

if ( locu->adj == NULL ) /* item added at the begining */

{

locu->adj = tmp;

return ;

}

ptr = locu->adj;

while ( ptr->link != NULL )

ptr = ptr->link;

ptr->link = tmp;

} /*End of insert_edge()*/

struct node *find( char item )

{

struct node *ptr, *loc;

ptr = start;

while ( ptr != NULL )

{

if ( item == ptr->name )

{

loc = ptr;

return loc;

}

else

ptr = ptr->next;

}

loc = NULL;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 55

Page 56: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

return loc;

} /*End of find()*/

del_edge( char u, char v )

{

struct node * locu, *locv;

struct edge *ptr, *tmp, *q;

locu = find( u );

if ( locu == NULL )

{

printf( "Source node not present\n" );

return ;

}

if ( locu->adj->dest == v )

{

tmp = locu->adj;

locu->adj = locu->adj->link; /* first element deleted */

free( tmp );

return ;

}

q = locu->adj;

while ( q->link->link != NULL )

{

if ( q->link->dest == v ) /* element deleted in between */

{

tmp = q->link;

q->link = tmp->link;

free( tmp );

return ;

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 56

Page 57: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

q = q->link;

} /*End of while*/

if ( q->link->dest == v ) /* last element deleted */

{

tmp = q->link;

free( tmp );

q->link = NULL;

return ;

}

printf( "This edge not present in the graph\n" );

} /*End of del_edge()*/

display()

{

struct node * ptr;

struct edge *q;

ptr = start;

while ( ptr != NULL )

{

printf( "%c ->", ptr->name );

q = ptr->adj;

while ( q != NULL )

{

printf( " %c", q->dest );

q = q->link;

}

printf( "\n" );

ptr = ptr->next;

}

} /*End of display()*/

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 57

Page 58: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE OUTPUT:

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :1

Enter a node to be inserted:1

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :1

Enter a node to be inserted:2

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :1

Enter a node to be inserted:3

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 58

Page 59: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

4.Display

5.Exit

Enter your choice :5

1 ->

2 ->

3 ->

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :2

Enter an edge to be inserted:1 2

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :2

Enter a edge to be inserted:2 3

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :2

Enter a fdge to be inserted:3 1

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 59

Page 60: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :5

1 ->2

2 ->3

3 ->1

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :3

Enter a node to be deleted:3

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :5

1 ->2

2->

GRAPH OPERATIONS

1.Insert a node

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 60

Page 61: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :4

Enter an edge to be deleted:1 2

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :5

1 ->

2 ->

GRAPH OPERATIONS

1.Insert a node

2.Insert an edge

3.Delete an edge

4.Display

5.Exit

Enter your choice :6

EXERCISE:6

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 61

Page 62: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

AIM:To implement Depth First Search for a graph nonrecursively.

DESCRIPTION:

Graph: A graph is a collection of nodes called vertices, and a collection of segments called

lines, connecting parts of vertices.

Graph Traversals: Traversal means visiting each node at least once in a graph. There are

multiple paths to a vertex we may arrive at it from more than one direction as we traverse

the graph.

The traditional solution to this problem is to introduce a visited flag at each vertex.

Before the traversal we can set the visited flag in each vertex to off. Then, as we set

the visited flag to on to indicate that the data have been processed.

Depth First Search:

“STACK” data structure is suitable to achieve data first structure. “Stack” is a lost in first out

structure.

Stack data structure is used to traverse the graph in DFS manner.

As the algorithm proceeds, nodes status will be changed.

Initially, we assume all the nodes will be in un-processed state.

When they are in stack, we assume they are in the ready state.

When they leave the stack, we consider them that they are processed.

DFS ALGORITHM:

Step 1: Initialization

a) Initialize stack to empty.

b) Mark all nodes as not visited.Push node 0 onto the stack and

mark it as visited.

Step 2: While (stack is not empty)

{

a) Pop value from stack.

b) Push all nodes adjacent to popped node and which have not

been visited as yet onto the stack.

c) Mark all pushed nodes as visited.

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 62

Page 63: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

/*To implement Depth first search of a graph non-recursively*/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

int adj[5][5]={{0,1,1,1,0},

{1,0,1,0,1},

{1,1,0,1,0},

{1,0,1,0,1},

{0,1,0,1,0}};

int visited[30];

struct stack

{

int s[30];

int sp;

};

typedef struct stack stk;

stk st;

void push(int val);

int pop();

int isempty();

void disp();

void main()

{

int i,j,val;

int dfs[30];

st.sp=-1;

clrscr();

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

{

printf(“\n”);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 63

Page 64: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

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

printf(“%d\t”,adj[i][j]);

}

i=0;

push(i);

visited[i]=1;

disp();

while(isempty()==0)

{

val=pop();

dfs[i]=val;

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

{

if(adj[val][j]==1)

{

if(visited[j]==0)

{

push(j);

visited[j]=1;

}

}

}

disp();

i=i+1;

}

printf(“\nDfs for the graph”);

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

printf(“%d\t”,dfs[i]);

getch();

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 64

Page 65: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

int isempty()

{

if(st.sp==-1)

{

return1;

}

else

return0;

}

void push(int val)

{

st.sp++;

st.s[st.sp]=val;

}

int pop()

{

int val,ans;

ans=isempty();

if(ans==0)

{

val=st.s[st.sp];

st.sp--;

}

else

printf(“\n stack is empty “);

return(val);

}

void disp()

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 65

Page 66: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

int i;

printf(“\n”);

if(isempty()==0)

{

printf(“\n Elements of stack”);

for(i=st.sp;i>=0;i--)

printf(“\n%d\t”,st.s[i]);

}

}

EXPECTED OUTPUT:

0 1 1 1 01 0 1 0 11 1 0 1 01 0 1 0 10 1 0 1 0

Elements of stack

0

Elements of stack

3

2

1

Elements of stack

4

2

1

Elements of stack

2

1

Elements of stack

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 66

Page 67: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

1

Dfs for the graph

0 3 4 2 1

Exercise7:

AIM: Program for Breadth First Search algorithm

DESCRIPTION:

Graph:

A graph is a collection of nodes called vertices and collection ofsegments called lines

connecting parts of vertices.

Graph Traversals:

Traversals means visiting each node atleast once in a graph.There are multiple paths to

a vertex.We may arrive at it from more than one direction as we traverse the graph.

The traditional solution to this problem is to include a visited flag at each vertex.

Before the traversal we set the visited flag in each vertex to off.Then,as we traverse

the graph,we set the visited flag to on to indicate that the data have been processed.

Breadth First search:

Data structure “Queue” is used for “BFS”.

“Queue” is a First In First Out (FIFO) structure.

Queue Data structure is used to traverse the graph in BFS manner.

As the algorithm proceeds,nodes status will be changed.

Initially,we assume all the nodes will be in un-processed state.

When they are in Queue,we assume they are in ready state.

When they leave the Queue,we consider them that they are processed.

BFS ALGORITHM:

Step 1: Initialization

a) Initialize Queue to empty.

b) Mark all nodes as not visited.

c) Insert node “0” and mark it as visited.

Step 2: while(Queue is not empty)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 67

Page 68: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

Delete element from Queue.

d) Insert nodes adjacent to deleted node and which have not been visited.

e) Mark all inserted nodes as visited. }

SAMPLE PROGRAM:/*program for Breadth first search */

#include<stdio.h>

#include<conio.h>

int adj[30][30];

int visited[30];

struct queue

{

int data[30];

int front,rear;

};

typedef struct queue que;

que q;

void insert(int val);

int delete();

int isempty();

void disp();

void main()

{

int nodes;

int i,j,val;

int bfs[30];

q.rear=-1;

q.front=0;

clrscr();

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 68

Page 69: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf(“\n enter number of nodes in the graph”);

scanf(“%d”,&nodes);

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

{

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

{

printf(“n enter edges[%d][%d]”,i,j);

scanf(“%d”,&adj[i][j]);

}

}

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

{

printf(“\n”);

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

printf(“%d\t”,adj[i][j]);

}

i=0;

insert(i);

visited[i]=1;

disp();

while(isempty()==0)

{

val=delete();

bfs[i]=val;

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

{

if(adj[val][j]==1)

{

if(visited[j]==0)

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 69

Page 70: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

insert(j);

visited[j]=1;

}

}

}

disp() ;

i=i+1;

}

printf(“\n BFS for the graph \n”);

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

printf(“%d\t”,BFS[i]);

getch();

}

void insert(int val)

{

q.rear++;

q.data[q.rear]=val;

}

int delete()

{

int k,ans;

k=isempty();

if(k==0)

{

ans=q.data[q.front];

q.front++;

}

else

{

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 70

Page 71: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf(“Queue is empty”);

ans=-1;

}

return(ans);

}

int isempty()

{

int ans;

if(q.rear<q.front)

ans=1;

else

ans=0;

return(ans);

}

void disp()

{

int ans,I;

printf(“data elements in Queue:\n”);

ans=isempty();

if(ans==0)

{

for(i=q.front;i<=q.rear;i++)

printf(“%d\n”,q.data[i]);

}

else

printf(“Queue is empty \n”);

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 71

Page 72: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE OUTPUT :

Enter no.of nodes in the graph: 4

Enter edges[0][0]: 0Enter edges[0][1]: 1Enter edges[0][2]: 1Enter edges[0][3]: 1 Enter edges[1][0]: 0Enter edges[1][1]: 0 Enter edges[1][2]: 0Enter edges[1][3]: 1Enter edges[2][0]: 0Enter edges[2][1]: 0 Enter edges[2][2]: 0Enter edges[2][3]: 1Enter edges[3][0]: 0Enter edges[3][1]: 0Enter edges[3][2]: 0Enter edges[3][3]: 00 1 1 1

0 0 0 1

0 0 0 1

0 0 0 0

Data elements in the Queue

0

Data elements in the Queue

3

2

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 72

Page 73: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

1

Data elements in the Queue

2

1

Data elements in the Queue

1

Data elements in the Queue

Queue is empty

Bfs for the graph 0 3 2 1

EXERCISE-8:

AIM: To implement KRUSKAL'S algorithm to generate a min-cost spanning tree.

DESCRIPTION:

Spanning tree: Let G be a graph containing n verticies.Then a tree which is derived from Gis

called spanning tree if and only if the number of verticies in G should like in the derived tree

Minimal Spanning Tree:A spanning tree whose total weight is least among the group of

spanning trees is said to be “Minimal Spanning Tree”.

KRUSKAL’S Algorithm:KRUSKAL’Salgorithm builds a minimum spanning tree by adding at

each step the smallest weighted edge that has not all ready been added,provided it does

not create a cycle.The algorithm stops when all edges are connected.

Algorithm:

Step1:Let G ={V,E} be a graph

Step2:MST={} //MST is the set of all edges that make up minimal spanning tree

Step3:Select the starting node

While(MST has <n-1 edges) && (Eis not empty)

{

3.1.Select(u,v) from E such that its weight is minimal

3.2. delete (u,v) from E

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 73

Page 74: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

3.3. If adding (u.v) does not create a cycle,then add it to MST.

}

SAMPLE PROGRAM:

/* program to find minimum spanning tree using KRUSKAL’S Algorithm */

#include<stdio.h>

#define INF 1000

char vertex[10];

int wght[10][10];

int span_wght[10][10];

int source

struct Sort

{

int v1,v2;

int weight;

}que[20];

int n,ed,f,r;

int cycle(int s,int d)

{

int j,k;

if(source==d)

return 1;

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

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 74

Page 75: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

if(span_wght[d][j]!=INF && s!=j)

{

if(cycle(d,j))

return 1;

}

return 0;

}

void build_tree()

{

int i,j,w,k,count=0;

for(count=0;count<n;f++)

{

i=que[f].v1;

j=que[f].v2;

w=que[f].weight;

span_wght[i][j]=span_wght[j][i]=w;

source=i;

k=cycle(i,j);

if(k)

span_wght[i][j]=span_wght[j][i]=INF;

else

count++;

}

}

void swap(int *i,int *j)

{

int t;

t=*i;

*i=*j;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 75

Page 76: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

*j=t;

}

void main()

{

int i,j,k=0,temp;

int sum=0;

clrscr();

printf("\n\n\tKRUSKAL'S ALGORITHM TO FIND SPANNING TREE\n\n");

printf("\n\tEnter the No. of Nodes : ");

scanf("%d",&n);

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

{

printf("\n\tEnter %d value : ",i+1);

fflush(stdin);

scanf("%c",&vertex[i]);

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

{

wght[i][j]=INF;

span_wght[i][j]=INF;

}

}

printf("\n\nGetting Weight\n");

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

for(j=i+1;j<n;j++)

{

printf("\nEnter 0 if path Doesn't exist between %c to %c : ",vertex[i],vertex[j]);

scanf("%d",&ed);

if(ed>=1)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 76

Page 77: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

wght[i][j]=wght[j][i]=ed;

que[r].v1=i;

que[r].v2=j;

que[r].weight=wght[i][j];

if(r)

{

for(k=0;k<r;k++)

if(que[k].weight>que[r].weight)

{

swap(&que[k].weight,&que[r].weight);

swap(&que[k].v1,&que[r].v1);

swap(&que[k].v2,&que[r].v2);

}

}

r++;

}

}

clrscr();

printf("\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n");

printf("\n\tweight matrix\n\n\t");

for(i=0;i<n;i++,printf("\n\t"))

for(j=0;j<n;j++,printf("\t"))

printf("%d",wght[i][j]);

build_tree();

printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");

printf("\n\t\tLIST OF EDGES\n\n");

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

for(j=i+1;j<n;j++)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 77

Page 78: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

if(span_wght[i][j]!=INF)

{

printf("\n\t\t%c ------ %c = %d ",vertex[i],vertex[j],span_wght[i][j]);

sum+=span_wght[i][j];

}

printf("\n\n\t\tTotal Weight : %d ",sum);

getch();

}

EXPECTED OUTPUT:

KRUSKAL’S ALGORITHM TO FIND SPANNING TREEEnter the No. of Nodes:5

Enter 1 value:1

Enter 2 value:2

Enter 3 value:3

Enter 4 value:4

Enter 5 value:5

Getting Weight:

Enter 0 if path doesn’t exist between 1 to 2:2Enter 0 if path doesn’t exist between 1 to 2:4Enter 0 if path doesn’t exist between 1 to 2:3Enter 0 if path doesn’t exist between 1 to 2:0Enter 0 if path doesn’t exist between 1 to 2:0Enter 0 if path doesn’t exist between 1 to 2:2Enter 0 if path doesn’t exist between 1 to 2:1Enter 0 if path doesn’t exist between 1 to 2:1Enter 0 if path doesn’t exist between 1 to 2:0Enter 0 if path doesn’t exist between 1 to 2:4

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 78

Page 79: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

ORIGINAL GRAPH WEIGHT MATRIX

Weight matrix

1000 2 4 3 10002 1000 1000 2 14 1000 1000 1 10003 2 1 1000 41000 1 1000 4 1000

MINIMUM SPANNING TREE

LIST OF EDGES

1------2=22------4=22------5=13------4=1

Total Weight:6

Exercise 9:

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

DESCRIPTION:

Spanning tree: Let G be a graph containing n verticies.Then a tree which is derived from Gis

called spanning tree if and only if the number of verticies in G should like in the derived tree

Minimal Spanning Tree:A spanning tree whose total weight is least among the group of

spanning trees is said to be “Minimal Spanning Tree”.

PRIM’S Algoritham:PRIM’S algorithm builds a minimum spanning tree by deleting the edges

sequentially that does not effect the graph.i.e that does not disconnect the graph until n-1

edges remain.

Algorithm:

Step1:Let G ={V,E} be a graph

Step2:MST={}//MST is the set of all edges that make up minimal spanning tree

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 79

Page 80: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Step3:Select the starting node

While(MST has <n-1 edges) && (Eis not empty)

{

3.1.Select a node from adjacent nodes to the node selected such that its

Weight is minimal.

3.2. If deletion of that edge does not disconnect the graph then delete edge

(u,v) from E.Otherwise add it to MST

}

SAMPLE PROGRAM:

/* program to implement prim’s algorithm*/

#include<stdio.h>

#define INF 1000

int vertex[10];

int wght[10][10];

int new_wght[10][10];

int closed[10];

int n;

int inclose(int i,int n1)

{

/*chk for the ith vertex presence in closed*/

int j;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 80

Page 81: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

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

if(closed[j]==i)

return 1;

return 0;

}

void buildtree()

{

int i=0,j,count=0;

int min,k,v1=0,v2=0;

closed[0]=0;

while(count<n-1)

{

min=INF;

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

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

if(wght[closed[i]][j]<min && !inclose(j,count))

{

min=wght[closed[i]][j];

v1=closed[i];

v2=j;

}

new_wght[v1][v2]=new_wght[v2][v1]=min;

count++;

closed[count]=v2;

printf("\nScan : %d %d---------%d wght = %d \n",count,v1+1,v2+1,min);

getch();

}

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 81

Page 82: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

void main()

{

int i,j,ed,sum=0;

clrscr();

printf("\n\n\tPRIM'S ALGORITHM TO FIND SPANNING TREE\n\n");

printf("\n\tEnter the No. of Nodes : ");

scanf("%d",&n);

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

{

vertex[i]=i+1;

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

{

wght[i][j]=INF;

new_wght[i][j]=INF;

}

}

printf("\n\nGetting Weight.\n");

printf("\n\tEnter 0 if path doesn't exist between {v1,v2} else enter the wght\n");

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

for(j=i+1;j<n;j++)

{

printf("\n\t%d -------- %d : ",vertex[i],vertex[j]);

scanf("%d",&ed);

if(ed>=1)

wght[i][j]=wght[j][i]=ed;

}

getch();

clrscr();

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 82

Page 83: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf("\n\n\t\tNODES CURRENTLY ADDED TO SPANNING TREE\n\n");

buildtree();

printf("\n\tNEW GRAPH WEIGHT MATRIX\n\n");

printf("\n\tweight matrix\n\n\t");

for(i=0;i<n;i++,printf("\n\t"))

for(j=0;j<n;j++,printf("\t"))

printf("%d",new_wght[i][j]);

printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");

printf("\n\t\tLIST OF EDGES\n\n");

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

for(j=i+1;j<n;j++)

if(new_wght[i][j]!=INF)

{

printf("\n\t\t%d ------ %d = %d ",vertex[i],vertex[j],new_wght[i][j]);

sum+=new_wght[i][j];}

printf("\n\n\t Total Weight : %d ",sum);

getch();

}

EXPECTED OUTPUT:

Enter the No. of Nodes:5

Getting Weight:

Enter 0 if path doesn’t exist between {v1,v2} else enter the wght 1--------2:2 2--------3:4 1--------4:3 1--------5:0 2--------3:0 2--------4:2 2--------5:1

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 83

Page 84: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

3--------4:1 3--------5:0 4--------5:4

NODES CURRENTLY ADDED TO SPANNING TREE

Scan:1 1---------2 Wght=2Scan:2 2---------5 Wght=1Scan:3 2---------4 Wght=4Scan:4 4---------3 Wght=1

NEW GRAPH WEIGHT MATRIX

Weight matrix

1000 2 1000 10000 10002 1000 1000 2 11000 1000 1000 1 10001000 2 1 1000 10001000 1 1000 1000 1000

MINIMUM SPANNING TREE

LIST OF EDGES

1------2=22------4=22------5=13------4=1

Total Weight:6

EXERSICE10:

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

DESCRIPTION:

DIJKSTRA’S Algorithm:For finding shortest path by using Dijkstra’s algorithm we have given

a weighted graph and we need to find out minimum distance route between any given two

stations

Algorithm:

Step1:select the source node and mark it as processed

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 84

Page 85: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Step2: select all the stations i.e neighbours of source station and mark them as ready and

update their mininmum distances as the distances from source

Step3:Repeat step4 till destination station status becomes processed

Step4:Select the station which is having minimum distance out of the stations which are in

the ready status.Make status of selected station as processed and update all of its

unprocessed,and update ready state nodes minimum distance by adding distance from

selected station to that station and distance of selected station from source

SAMPLE PROGRAM:

/*program to implement dijkstra’s algorithm using priority queue*/

#include<stdio.h>

#include<stdlib.h>

int main()

{

int dist[10][10],sta[10],min[10],via[10];

int i,j,k,source,dest,amin,n,dd,t;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 85

Page 86: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

printf("Enter Number Of Nodes");

scanf("%d",&n);

printf("Enter Weights");

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

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

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

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

{

sta[i]=0;

min[i]=32767;

}

printf("Enter Source AND Destination indexes");

scanf("%d%d",&source,&dest);

k=source;

amin=0;

while(sta[dest]!=2)

{

sta[k]=2;

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

{

if(dist[k][i]&&sta[i]!=2)

{

dd=amin+dist[k][i];

if(dd<min[i])

{

min[i]=dd;

via[i]=k;

}

sta[i]=1;

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 86

Page 87: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

}

amin=32767;

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

if(sta[i]==1 && min[i]<amin)

{

amin=min[i];

k=i;

}

}

printf("Backtracking");

printf("%c->",'A'+dest);

for(k=via[dest];k!=source;k=via[k])

printf("%c->",'A'+k);

printf("%c",'A'+source);

return 0;

}

EXPECTED OUTPUT:

Enter Number Of Nodes:5

Enter Weights:

0 3 4 2 0

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 87

Page 88: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

3 0 0 6 7

4 0 0 1 0

2 6 1 0 5

0 7 0 5 0

Enter Source AND Destination indexes: 0 4

Backtracking:E->D->A

EXERCISE-11:

AIM: To implement BOYER-Moore algorithm for pattern matching.

DESCRIPTION: The Boyer-Moore algorithm scans the characters of the pattern from right to

left beginning with the rightmost character. During the testing of a possible placement of

pattern P against text T, a mismatch of text character T[i] = c with the corresponding pattern

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 88

Page 89: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

character P[j] is handled as follows: If c is not contained anywhere in P, then shift the

pattern P completely past T[i]. Otherwise, shift P until an occurrence of character c in P gets

aligned with T[i].This technique likely to avoid lots of needless comparisons by significantly

shifting pattern relative to text.

Last Function: We define a function last(c) that takes a character c from the alphabet and

specifies how far may shift the pattern P if a character equal to c is found in the text that

does not match the pattern

  index of the last occurrence

if c is in P

last(c)

of c in pattern P  

  -1 otherwise

For example consider

T: 0 1 2 3 4 5 6 7 8 9a b a c A A B A C C

P: a b a C A B0 1 2 3 4 5

last(a) is the index of the last (rightmost) occurrence of 'a' in P, which is 4.

last(c) is the index of the last occurrence of c in P, which is 3

'd' does not exist in the pattern there we have last (d) = -1.

c A B C Dlast(c) 4 3 -1

Now, for 'b' notice

T: a b A C A a B a C cP: a b A C A b

Therefore, last(b) is the index of last occurrence of b in P, which is 5

The complete last(c) function

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 89

Page 90: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

c A B C Dlast(c) 4 5 3 -1

Boyer-Moore algorithm :

BOYER_MOORE_MATCHER (T, P)

Input: Text with n characters and Pattern with m charactersOutput: Index of the first substring of T matching P

1. Compute function last2. i ← m-13. j ← m-14. Repeat5. If P[j] = T[i] then6. if j=0 then7. return i // we have a match8. else 9. i ← i -110. j ← j -111. else12. i ← i + m - Min(j, 1 + last[T[i]])13. j ← m -114. until i > n -115. Return "no match"

SAMPLE PROGRAM:

#include<stdio.h>

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 90

Page 91: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

#include<conio.h>

void preBmBc(char *x, int m, int bmBc[ ])

{

int i;

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

bmBc[i] = m;

for (i = 0; i < m - 1; ++i)

bmBc[x[i]] = m - i - 1;

}

void suffixes(char *x, int m, int *suff)

{

int f, g, i;

suff[m - 1] = m;

g = m - 1;

for (i = m - 2; i >= 0; --i)

{

if (i > g && suff[i + m - 1 - f] < i - g)

suff[i] = suff[i + m - 1 - f];

else {

if (i < g)

g = i;

f = i;

while (g >= 0 && x[g] == x[g + m - 1 - f])

--g;

suff[i] = f - g;

}

}

}

void preBmGs(char *x, int m, int bmGs[])

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 91

Page 92: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

int i, j, suff[XSIZE];

suffixes(x, m, suff);

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

bmGs[i] = m;

j = 0;

for (i = m - 1; i >= 0; --i)

if (suff[i] == i + 1)

for (I=1; j < m - 1 - i; ++j)

if (bmGs[j] == m)

bmGs[j] = m - 1 - i;

for (i = 0; i <= m - 2; ++i)

bmGs[m - 1 - suff[i]] = m - 1 - i;

}

void BM(char *x, int m, char *y, int n)

{

int i, j, bmGs[XSIZE], bmBc[ASIZE];

/* Preprocessing */

preBmGs(x, m, bmGs);

preBmBc(x, m, bmBc);

/* Searching */

j = 0;

while (j <= n - m)

{

for (i = m - 1; i >= 0 && x[i] == y[i + j]; --i);

if (i < 0) {

OUTPUT(j);

j += bmGs[0];

}

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 92

Page 93: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

else

j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i);

}

}

void main( )

{

char *x,*y;

int bmBc[ ], bmGs[ ] ,*suff

char *p="advanced data structures";

char *q="nced";

int m=strlen(p);

int n=strlen(q);

}

EXPECTED OUTPUT:

Pattern nced is present in text:

inadvanced data structures

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 93

Page 94: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

EXERCISE-12:

AIM: To implement Knuth-Morris-Pratt algorithm for pattern matching.

DESCRIPTION:

DEFINITION: The KMP algorithm compares the pattern to the text in left-to-right, but shifts

the pattern, P more intelligently than the brute-force algorithm. When a mismatch occurs,

what is the most we can shift the pattern so as to avoid redundant comparisons. The answer

is that the largest prefix of P[0..j] that is a suffix of P[1..j]

EXPLANATION:The Knuth–Morris–Pratt string searching algorithm searches for occurrences

of a "word" W within a main "text string" S by employing the observation that when a

mismatch occurs, the word itself embodies sufficient information to determine where the

next match could begin, thus bypassing re-examination of previously matched characters.

• performs the comparisons from left to right;

• preprocessing phase in O(m) space and time complexity;

• searching phase in O(n+m) time complexity (independent from the alphabet size);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 94

Page 95: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM:

/*Program to implement Knuth-Morris-Pratt pattern matching */

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void cp(char p[],int pp[])

{

int q,k,m;

m=strlen(p);

pp[1]=0;

k=0;

for(q=2;q<m;q++)

{

while(k>0 && p[k+1]!=p[q])

k=pp[k];

if(p[k+1]==p[q])

k=k+1;

pp[q]=k;

}

}

void kmp(char t[],char p[])

{

int pp[50],i,q,k,m,n;

n=strlen(t);

m=strlen(p);

cp(p,pp);

q=0;

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

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 95

Page 96: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

{

while(q>0 && p[q+1]!=t[i])

q=pp[q];

if(p[q+1]==t[i])

q++;

if(q==m-1)

{

printf("String Found");

break;

}

}

if(i==n)

printf("String Not Found");

}

void main()

{

char t[100],p[50];

clrscr();

printf("Enter Actual String");

scanf("%s",&t);

printf("Enter String To Be Found");

scanf("%s",&p);

kmp(t,p);

getch();

}

EXPECTED OUTPUT:

Enter Actual String:acaabcaaba

Enter String To Be Found:bca

String Found

Enter actual String:aaabbbacaaa

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 96

Page 97: ADS R10 LAB MANUAL IN C

ADVANCED DATASTRUCTURES LAB MANUAL

Enter String To Be Found:bca

String Not Found

EXERCISE 13:AIM: To implement a program for Radix sortDESCRIPTION:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY 97


Recommended