gudlavalleru engineering college seshadri rao...

88
III B.Tech ADVANCED DATA STRUTURES LAB Page | 1 Department of Computer Science & Engineering GEC GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao Knowledge Village, Gudlavalleru Academic Year: 201314, Semester : I Class: III B.Tech Branch: CSE Subject: Advanced Data Structures Lab ==================================================================== List of experiments: 1. To implement functions of Dictionary using Hashing (i).Division Method (ii).Multiplication Method (iii).Universal Hashing 2. To perform various operations i.e, insertions and deletions on AVL trees 3. To perform various operations i.e., insertions and deletions on 2-3 trees. 4. To implement operations on binary heap. 5. To implement operations on graphs (i) Vertex insertion (ii) Vertex deletion (iii) Finding vertex (iv) Edge addition and deletion 6. To implement Depth First Search for a graph nonrecursively. 7. To implement Breadth First Search for a graph nonrecursively. 8. To implement Prim’s algorithm to generate a min-cost spanning tree. 9. To implement Krushkal’s algorithm to generate a min-cost spanning tree. 10. To implement Dijkstra’s algorithm to find shortest path in the graph. 11. To implement pattern matching using Boyer-Moore algorithm. 12. To implement Knuth-Morris-Pratt algorithm for pattern matching.

Upload: hoangkhue

Post on 14-Apr-2018

222 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 1 Department of Computer Science & Engineering GEC

GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao Knowledge Village, Gudlavalleru

Academic Year: 2013–14, Semester : I

Class: III B.Tech Branch: CSE Subject: Advanced Data Structures Lab

====================================================================

List of experiments:

1. To implement functions of Dictionary using Hashing

(i).Division Method

(ii).Multiplication Method

(iii).Universal Hashing

2. To perform various operations i.e, insertions and deletions on AVL trees

3. To perform various operations i.e., insertions and deletions on 2-3 trees.

4. To implement operations on binary heap.

5. To implement operations on graphs

(i) Vertex insertion

(ii) Vertex deletion

(iii) Finding vertex

(iv) Edge addition and deletion

6. To implement Depth First Search for a graph nonrecursively.

7. To implement Breadth First Search for a graph nonrecursively.

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

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

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

11. To implement pattern matching using Boyer-Moore algorithm.

12. To implement Knuth-Morris-Pratt algorithm for pattern matching.

Page 2: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 2 Department of Computer Science & Engineering GEC

EXERCISE: 1

AIM:

Program to implement functions of Dictionary using Hashing

(i).Division Method

(ii).Multiplication Method

(iii).Universal Hashing

DESCRIPTION:

DICTIONARIES:

A dictionary is a collection of Paris of the form (k,v) where k is a key and v is the value

associated with the key k . No two pairs in a dictionary have the same key.

A Dictionary may be maintained as an ordered linear list and can be represented using skip lists and

hashing.. This method uses a hash function to map dictionary pairs into positions in a table called the

hash table. In the ideal situation, if pair p has the key k and f is the hash function, then p is stored in

position f(k) of the table. Assume for now that each position of the table can store at most one pair.

To search for a pair with key k, we compute f(k) and see whether a pair exists at position f(k) of the

table. If so, we have found the desired pair. If not, the dictionary contains no pair with the specified

key k. in the former case the pair may be deleted by making position f(k) of the table empty. In the

latter case the pair may be inserted by placing it in position f(k).

HASH TABLES: An extremely effective and practical way of implementing dictionaries. O(1) time

for search, insert, and delete in the average case. O(n) time in the worst case; by careful design, we

can make the probability that more than constant time is required to be arbitrarily small.

Types of Hash Tables:

1. Open or External

2. Closed or Internal

Open Hashing:

Let:

1. U be the universe of keys:

integers

character strings

complex bit patterns

2. B the set of hash values (also called the buckets or bins).Let B = {0, 1,..., m - 1}where m > 0 is

a positive integer.

A hash function h: U B associates buckets (hash values) to keys.

Page 3: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 3 Department of Computer Science & Engineering GEC

Two main issues:

1. Collisions: If x1 and x2 are two different keys, it is possible that h(x1) = h(x2). This is called a

collision. Collision resolution is the most important issue in hash table implementations.

2. Hash Functions: Choosing a hash function that minimizes the number of collisions and also

hashes uniformly is another critical issue.

Collision Resolution by Chaining:

Put all the elements that hash to the same value in a linked list. See the following Figure 1.

Figure 1: Collision resolution by chaining

Example: See the following Figure 2. Consider the keys 0, 1, 4, 9, 16, 25, 36, 49, 64, 81,100.

Let the hash function be:h(x) = x % 7

Figure 2: Open hashing: An example

Bucket lists:

unsorted lists

Page 4: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 4 Department of Computer Science & Engineering GEC

sorted lists (these are better)

Insert (x, T) : Insert x at the head of list T[h(key (x))]

Search (x, T): Search for an element x in the list T[h(key (x))]

Delete (x, T) : Delete x from the list T[h(key (x))]

Worst case complexity of all these operations is O (n)

In the average case, the running time is O(1 + ), where

= load factor

(1.1)

n = number of elements stored (1.2)

m = number of hash values or buckets

It is assumed that the hash value h(k) can be computed in O(1) time. If n is O(m), the average case

complexity of these operations becomes O(1) !

Closed Hashing:

1. All elements are stored in the hash table itself.

2. Avoids pointers; only computes the sequence of slots to be examined.

3. Collisions are handled by generating a sequence of rehash values.

H: x {0, 1, 2,..., m - 1}

Given a key x, it has a hash value h(x,0) and a set of rehash valuesh(x, 1), h(x,2), . . . , h(x, m-1)

We require that for every key x, the probe sequence< h(x,0), h(x, 1), h(x,2), . . . , h(x, m-1)> be a

permutation of <0, 1, ..., m-1>.

This ensures that every hash table position is eventually considered as a slot for storing a record with

a key value x.

1. Search (x, T): Search will continue until you find the element x (successful search) or an

empty slot (unsuccessful search).

2. Delete (x, T): No delete if the search is unsuccessful.If the search is successful, then put the

label DELETED (different from an empty slot).

3. Insert (x, T): No need to insert if the search is successful.If the search is unsuccessful, insert

at the first position with a DELETED tag.

Rehashing Methods:

Denote h(x, 0) by simply h(x).

Linear probing : h(x, i) = (h(x) + i) mod m

Quadratic Probing : h(x, i) = (h(x) + C1i + C2i2) mod mWhere C1 and C2 are constants

Double Hashing: h(x, i) = (h(x) + i h’(x)) mod m

A Comparison of Rehashing Methods

Page 5: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 5 Department of Computer Science & Engineering GEC

m distinct probe

sequences

Primary clustering

m distinct probe

sequences

No primary clustering;

but secondary clustering

m2 distinct probe

sequences

No primary clustering

No secondary clustering

An Example:Assume linear probing with the following hashing and rehashing functions:

h(x, 0) = x%7

h(x, i) = (h(x, 0) + i)%7

Start with an empty table.

Search (35, T) 0 14

Delete (9, T) 1 empty

2 30

3 deleted

4 45

5 empty

6 20

Insert (20, T) 0 14

Insert (30, T) 1 empty

Insert (9, T) 2 30

Insert (45, T) 3 9

Insert (14, T) 4 45

5 empty

6 20

Delete (45, T) 0 14

Insert (16, T) 1 empty

2 30

3 10

4 16

5 empty

6 20

Search (45, T) 0 14

Search (52, T) 1 empty

Search (9, T) 2 30

Insert (45, T) 3 10

Insert (10, T) 4 45

5 empty

6 20

Page 6: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 6 Department of Computer Science & Engineering GEC

Program:

#include<stdio.h>

#include<conio.h>

int htable[20],h,op,key,m,i,pos,count=0,flag;

void main()

{

clrscr();

printf("\nEnter Hash Table Size:");

scanf("%d",&m);

printf("-------------HASH FUNCTIONS--------------");

printf("\n[1].Division\n[2].Multiplication\n[3].Universal");

printf("\nChoose Hash Function:");

scanf("%d",&h);

do

{

printf("--------------OPERATIONS ON DICTIONARIES--------------\n");

printf("\t[1].INSERT\n\t[2].DELETE\n\t[3].SEARCH\n\t[4].DISPLAY\n\t[0].EXIT");

printf("\nEnter Operation:");

scanf("%d",&op);

switch(op)

{

case 1: if(count<m)/* checking if the Hash table is already FULL */

{

Page 7: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 7 Department of Computer Science & Engineering GEC

generatepos();/* finding location using h(k) */

insert();

}

else printf("\nHash Table is Full");

break;

case 2: if(count==0)/* checking if the Hash table is EMPTY */

printf("\nHash Table is Empty");

else

{

generatepos();

delete();

}

break;

case 3: if(count==0)

printf("\nHash Table is Empty");

else

{

generatepos();

if(search(key)==-1)/* If search is unsuccessful */

printf("\nKey Not Found in the Hash Table");

else

printf("\nKey Found At Location:%d",search(key));

}

break;

Page 8: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 8 Department of Computer Science & Engineering GEC

case 4: if(count==0)

printf("\nHash Table is Empty");

else

display();

break;

}

}while(op!=0);

}

generatepos()

{

printf("Enter Key:");

scanf("%d",&key);

if(h==1)

pos=division(key);

else if(h==2)

pos=multiply(key);

else

pos=universal(key);

}

int division(int k)

{

return (k%m); /* hash function h(k)=(k%m) */

Page 9: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 9 Department of Computer Science & Engineering GEC

}

int multiply(int k)

{

/* hash function h(k)=floor(m*(kA-|kA|)) */

float a=0.61804,t2;

int t1;

t1=(k*a); /* |kA| */

t2=(k*a); /* kA */

t2=t2-t1; /* kA - |kA| */

pos=t2*m;

return pos;

}

int universal(int k)

{

/* hash function h(k)=(a*k+b)%p)%m); a,b, p are prime numbers where a,b<m and p>=m */

/* a and b constant primes < m */

/* p is prime > m */

int p=13,a=7,b=5;

pos=((a*k+b)%p)%m;

return pos;

}

insert()

{

flag=0;

Page 10: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 10 Department of Computer Science & Engineering GEC

if(search(key)==-1) /* If search is Unsuccessful */

{

/* searching circularly until an empty location is found */

while(flag==0)

{

if(htable[pos]==0)/* if location is empty */

{

htable[pos]=key; /* Inserting key */

printf("\nKey Inserted at Location: %d",pos);

count++;

flag=1;

break;

}

else /* Collision */

{

printf("\nCollision Occured at Location:%d",pos);

pos=(pos+1)%m; /* Linear probing */

}

}

}

else printf("\nKey is already present in the Hash Table");

}

delete()

{

Page 11: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 11 Department of Computer Science & Engineering GEC

flag=0;

if(search(key)!=-1)/* If search is Successful */

{

while(flag==0)/* searching for the key circularly */

{

if(htable[pos]==key)/* Key found */

{

htable[pos]=0; /* deleting key */

printf("\nKey Deleted from Location: %d",pos);

count--;

flag=1;

break;

}

else

pos=(pos+1)%m; /* linear probing */

}

}

else printf("\nKey Not Found in the Hash Table");

}

int search(int k)

{

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

{

if(htable[i]==k)

Page 12: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 12 Department of Computer Science & Engineering GEC

return i;

}

return -1;

}

display()

{

printf("\nElements in the Hash Table are:\n");

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

printf("%d\t",htable[i]);

}

Output:

(1).

Enter Hash Table Size:10

-------------HASH FUNCTIONS--------------

[1].Division

[2].Multiplication

[3].Universal

Choose Hash Function:1

--------------OPERATIONS ON DICTIONARIES--------------

[1].INSERT

[2].DELETE

[3].SEARCH

[4].DISPLAY

[0].EXIT

Page 13: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 13 Department of Computer Science & Engineering GEC

Enter Operation:1

Enter Key:123

Key Inserted at Location: 3

Enter Operation:1

Enter Key:133

Collision Occured at Location:3

Key Inserted at Location: 4

Enter Operation:1

Enter Key:234

Collision Occured at Location:4

Key Inserted at Location: 5

Enter Operation:4

Elements in the Hash Table are:

0 0 0 123 133 234 0 0 0 0

Enter Operation:1

Enter Key:222

Key Inserted at Location: 2

Enter Operation:1

Enter Key:232

Page 14: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 14 Department of Computer Science & Engineering GEC

Collision Occured at Location:2

Collision Occured at Location:3

Collision Occured at Location:4

Collision Occured at Location:5

Key Inserted at Location: 6

Enter Operation:4

Elements in the Hash Table are:

0 0 222 123 133 234 232 0 0 0

Enter Operation:2

Enter Key:111

Key Not Found in the Hash Table

Enter Operation:2

Enter Key:232

Key Deleted from Location: 6

Enter Operation:2

Enter Key:222

Key Deleted from Location: 2

Enter Operation:3

Enter Key:222

Key Not Found in the Hash Table

Enter Operation:2

Enter Key:222

Page 15: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 15 Department of Computer Science & Engineering GEC

Key Not Found in the Hash Table

Enter Operation:0

(2) Enter Hash Table Size:5

-------------HASH FUNCTIONS--------------

[1].Division

[2].Multiplication

[3].Universal

Choose Hash Function:2

--------------OPERATIONS ON DICTIONARIES--------------

[1].INSERT

[2].DELETE

[3].SEARCH

[4].DISPLAY

[0].EXIT

Enter Operation:1

Enter Key:22

Key Inserted at Location: 2

Enter Operation:1

Enter Key:23

Key Inserted at Location: 1

Enter Operation:2

Enter Key:34

Key Not Found in the Hash Table

Enter Operation:2

Enter Key:23

Key Deleted from Location: 1

Enter Operation:4

Elements in the Hash Table are:

0 0 22 0 0

Enter Operation:1

Enter Key:44

Key Inserted at Location: 0

Enter Operation:1

Enter Key:24

Key Inserted at Location: 4

Enter Operation:4

Page 16: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 16 Department of Computer Science & Engineering GEC

Elements in the Hash Table are:

44 0 22 0 24

Enter Operation:0

EXERCISE: 2 AIM:

Implementation of a C program to perform various operations i.e., insertions and deletions on

AVL trees.

Description: AVL Trees: Also called as: Height Balanced Binary Search Trees. Search, Insertion, and

Deletion can be implemented in worst case O (log n) time.

Definition: An AVL tree is a binary search tree in which

1. The heights of the right subtree and left subtree of the root differ by at most 1

2. The left subtree and the right subtree are themselves AVL trees

3. A node is said to be

left-high if the left subtree has

greater height /

right-high if the right subtree has

greater height

equal if the heights of the LST and

RST are the same -

Examples: Several examples of AVL trees are shown in

Figure1.

PROGRAM :

#include<stdio.h>

#include<conio.h>

Page 17: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 17 Department of Computer Science & Engineering GEC

struct avl

{

struct avl *lchild,*rchild;

int data,h;

};

#define max(a,b) (a>b?a:b)

int count=0;

int height(struct avl *root)

{

if(root==NULL)

return -1;

else

return root->h;

}

int isEmpty(struct avl *p)

{

return(p==NULL && count==0);

}

struct avl *findMin(struct avl *p)

{

if(p == NULL) return NULL;

else

{

if(p->lchild==NULL) return p;

Page 18: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 18 Department of Computer Science & Engineering GEC

else return findMin(p->lchild);

}

}

struct avl *search( struct avl *p,int x)

{

struct avl *t;

t = p;

while( t != NULL)

{

if(t->data == x)

return(t);

else if(t->data > x)

t = t->lchild;

else

t = t->rchild;

}

return(NULL);

}

struct avl *rotateRight(struct avl *root)

{

struct avl *t;

t=root->lchild;

root->lchild=t->rchild;

Page 19: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 19 Department of Computer Science & Engineering GEC

t->rchild=root;

root->h=max(height(root->lchild),height(root->rchild))+1;

t->h=max(height(t->lchild),height(t->rchild))+1;

return t;

}

struct avl *rotateLeft(struct avl *root)

{

struct avl *t;

t=root->rchild;

root->rchild=t->lchild;

t->lchild=root;

root->h=max(height(root->lchild),height(root->rchild))+1;

t->h=max(height(t->lchild),height(t->rchild))+1;

return t;

}

struct avl *RightBal(struct avl *root)

{

struct avl *t;

if(height(root->rchild)-height(root->lchild)==2)

{

t=root->rchild;

if((t->rchild->data>t->data) && (t->rchild!=NULL))

{

printf("\n\n\tRR(single left) Rotation");

Page 20: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 20 Department of Computer Science & Engineering GEC

root=rotateLeft(root);

}

else

{

printf("\n\n\tRL Rotation");

root->rchild=rotateRight(t);

root=rotateLeft(root);

}

}

return root;

}

struct avl *LeftBal(struct avl *root)

{

struct avl *t;

if(height(root->lchild)-height(root->rchild)==2)

{

t=root->lchild;

if((t->lchild->data<t->data) && (t->lchild!=NULL))

{

printf("\n\n\tLL(single right) Rotation");

root=rotateRight(root);

}

else

{

Page 21: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 21 Department of Computer Science & Engineering GEC

printf("\n\n\tLR Rotation");

root->lchild=rotateLeft(t);

root=rotateRight(root);

}

}

return root;

}

struct avl *insert(int x,struct avl *root)

{

if(root==NULL)

{

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

root->data=x;

root->h=0;

count++;

root->lchild=root->rchild=NULL;

printf("\n\tNode Inserted");

}

else if(x<root->data)

{

root->lchild=insert(x,root->lchild);

root=LeftBal(root);

}

else if(x>root->data)

Page 22: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 22 Department of Computer Science & Engineering GEC

{

root->rchild=insert(x,root->rchild);

root=RightBal(root);

}

root->h=max(height(root->lchild),height(root->rchild))+1;

return root;

}

struct avl *delete(int x,struct avl *p)

{

struct avl *temp;

if(x<p->data)

{

p->lchild = delete(x,p->lchild);

p=RightBal(p);

}

else if(x>p->data)

{

p->rchild = delete(x,p->rchild);

p=LeftBal(p);

}

else if(p->lchild && p->rchild)

{

temp = findMin(p->rchild);

Page 23: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 23 Department of Computer Science & Engineering GEC

p->data = temp->data;

p->rchild = delete(p->data,p->rchild);

p=LeftBal(p);

}

else

{

temp = p;

if(p->lchild==NULL) p=p->rchild;

else if(p->rchild==NULL) p=p->lchild;

free(temp);

printf("\n\tNode Deleted");

p->h=max(height(p->lchild),height(p->rchild))+1;

count--;

}

return p;

}

void inorder(struct avl *p)

{

if(p!=NULL)

{

inorder(p->lchild);

printf("%4d",p->data);

inorder(p->rchild);

Page 24: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 24 Department of Computer Science & Engineering GEC

}

}

void main()

{

struct avl *root=NULL;

struct avl *t=NULL;

int ch,x;

clrscr();

printf("\t\t----------------LIST OF OPERATIONS------------------");

printf("\n\t\t\t[1].INSERT");

printf("\n\t\t\t[2].TRAVERSAL");

printf("\n\t\t\t[3].DELETE");

printf("\n\t\t\t[0].EXIT");

do

{

printf("\n\n\tEnter Choice Of Operation:");

scanf("%d",&ch);

switch(ch)

{

case 1: printf("\n\tEnter Value:");

scanf("%d",&x);

if(search(root,x)==NULL)

root=insert(x,root);

Page 25: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 25 Department of Computer Science & Engineering GEC

else

printf("\n\tElement already present");

break;

case 2:if(!isEmpty(root))

{

printf("\n\tInorder Traversal:\t");

inorder(root);

}

else printf("\n\tAVL Tree Is Empty\n");

break;

case 3:if(!isEmpty(root))

{

printf("\n\tEnter Node To Be Deleted:");

scanf("%d",&x);

if(search(root,x)!=NULL)

root=delete(x,root);

else

printf("\n\tElement Not Found");

}

else printf("\n\tAVL Tree Is Empty\n");

break;

default:

if(ch!=0) printf("\n\tInvalid Choice Of Operation");

}

Page 26: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 26 Department of Computer Science & Engineering GEC

}while(ch!=0);

getch();

}

OUTPUT:

(1). ----------------LIST OF OPERATIONS------------------

[1].INSERT

[2].TRAVERSAL

[3].DELETE

[0].EXIT

Enter Choice Of Operation:1

Enter Value:12

Node Inserted

Enter Choice Of Operation:1

Enter Value:24

Node Inserted

Enter Choice Of Operation:1

Enter Value:20

RL Rotation

Enter Choice Of Operation:1

Enter Value:3

Node Inserted

Enter Choice Of Operation:4

Invalid Choice Of Operation

Enter Choice Of Operation:2

Page 27: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 27 Department of Computer Science & Engineering GEC

Inorder Traversal: 3 12 20 24

Enter Choice Of Operation:1

Enter Value:8

Node Inserted

LR Rotation

Enter Choice Of Operation:2

Inorder Traversal: 3 8 12 20 24

Enter Choice Of Operation:1

Enter Value:39

Node Inserted

Enter Choice Of Operation:1

Enter Value:78

Node Inserted

RR(Single left) Rotation

Enter Choice Of Operation:2

Inorder Traversal: 3 8 12 20 24 39 78

Enter Choice Of Operation:0

EXERCISE: 3

AIM:

Write a C program to perform various operations on 2-3 trees.

DESCRIPTION:

Definition: A 2-3 Tree is a null tree (zero nodes) or a single node tree (only one node) or a multiple

node tree with the following properties:

Each interior node has two or three children

Each path from the root to a leaf has the same length.

Fields of a Node:

Internal Node:

p1 k1 p2 k2 p3

p1:Pointer to the first child

p2:Pointer to the second child

Page 28: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 28 Department of Computer Science & Engineering GEC

p3:Pointer to the third child

k1:Smallest key that is a descendent of the second child

k2:Smallest key that is a descendent of the third child

Leaf Node:

key other fields

Note: Records are placed at the leaves. Each leaf contains a record (and key)

Example: See Figure1

Search: The values recorded at the internal nodes can be used to guide the search path.

To search for a record with key value x, we first start at the root. Let k1 and k2 be the two

values stored here.

1. If x < k1, move to the first child

2. If x >=k1 and the node has only two children, move to the second child

3. If x >=k1 and the node has three children, move to the second child if x < k2 and to the

third child if x >=k2.

Eventually, we reach a leaf. x is in the tree iff x is at this leaf.

Path Lengths:

A 2-3 Tree with k levels has between 2k - 1

and 3k - 1

leaves

Thus a 2-3 tree with n elements (leaves) requires

i. at least 1 + log3n levels

ii. at most 1 + log2n levels

ALGORITHM FOR INSERTIONS INTO 2-3 TREES: Insert (x):

1. Locate the node v, which should be the parent of x

2. If v has two children,

Figure 1: An example of a 2-3 tree

Page 29: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 29 Department of Computer Science & Engineering GEC

make x another child of v and place it in the proper order

adjust k1 and k2 at node v to reflect the new situation

3. If v has three children,

split v into two nodes v and v'. Make the two smallest among four children stay

with v and assign the other two as children of v'.

Recursively insert v' among the children of w where

w = parent of v

The recursive insertion can proceed all the way up to the root, making it necessary to

split the root. In this case, create a new root, thus increasing the number of levels by 1.

ALGORITHM FOR DELETIONS INTO 2-3 TREES:

Delete (x)

Locate the leaf L containing x and let v be the parent of L

Delete L. This may leave v with only one child. If v is the root, delete v and let its lone child

become the new root. This reduces the number of levels by 1. If v is not the root, let p =

parent of v, If p has a child with 3 children, transfer an appropriate one to v if this child is

adjacent (sibling) to v.

If children of p adjacent to v have only two children, transfer the lone child of v to an adjacent

sibling of v and delete v.

If p now has only one child, repeat recursively with p in place of v. The recursion can ripple

all the way up to the root, leading to a decrease in the number of levels.

Figure 2: Insertion in 2-3 trees: An example

Page 30: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 30 Department of Computer Science & Engineering GEC

PROGRAM:

/*2-3 TREE*/

#include<stdio.h>

#include<conio.h>

#define c 2

struct node

{

int data[c];

struct node *add[c+1];

}*root,*p,*l,*n,*n1;

int q[4],ele,i,j;

main()

Figure 3: Deletion in 2-3 trees: An Example

Page 31: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 31 Department of Computer Science & Engineering GEC

{

int ch;

root=NULL;

clrscr();

while(1)

{

printf("\n1.insert \t2.display\t3.exit");

ptintf(“\n enter your choice: “);

scanf("%d",&ch);

switch(ch)

{

case 1: printf("\nenter the value to be inserted: ");

scanf("%d",&ele);

p=n1=NULL;

insert();

break;

case 2: printf(“\nElements are :”);

display(root);

printf("\n");

break;

case 3:exit();

default:printf("wrong choice…\n");

}

}

getch();

}

insert()

{

int temp;

printf("enter the element\n");

scanf("%d",&ele);

if(root==NULL)

{

n=(struct node *)malloc(sizeof(struct node));

n->data[0]=ele;

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

n->add[i]=NULL;

n->data[1]=NULL;

root=n;

}

else

{

if(Search(p))

{

if(Is2Node(p))

{

p->data[1]=p->data[0];

Page 32: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 32 Department of Computer Science & Engineering GEC

if(ele<p->data[0])

p->data[0]=ele;

else

p->data[1]=ele;

p->add[1]=n1;

}

else

{

Split();

}

}

else

{

n=(struct node *)malloc(sizeof(struct node));

n->data[0]=ele;

n->data[1]=n->add[2]=NULL:

n->add[0]=p;

n->add[1]=n1;

root=n;

}

}

}

int Search(struct node *t)

{

l=root;

while(l!=t)

{

p=l;

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

{

if(l->data[i]!=NULL)

{

if(ele<l->data[i])

{

l=l->add[i];

break;

}

else if(i==1||l->data[i+1]==NULL)

{

l=l->add[i+1];

break;

}

}

}

}

if(p!=t)

Page 33: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 33 Department of Computer Science & Engineering GEC

return 0;

else

return 1;

}

int Is2Node(struct node *t)

{

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

if(t->data[i]==NULL)

return 0;

return 1;

}

Split()

{

int a,b,c;

a=Min(ele,p->data[0],p->data[1]);

b=Mid(ele,p->data[0],p->data[1]);

c=Max(ele,p->data[0],p->data[1]);

n=(struct node *)malloc(sizeof(struct node));

n->add[0]=p->add[2];

n->add[1]=n1;

n->add[2]=p->add[2]=NULL;

n->data[1]=p->data[1]=NULL;

p->data[0]=a;

n->data[0]=c;

n1=n;

ele=b;

insert();

}

int Min(int a,int b,int c)

{

if(a<b&&a<c)

return a;

else if(b<a&&b<c)

return b;

else

return c;

}

int Mid(int a,int b,int c)

{

if(a<b&&a>c||a>b&&a<c)

return a;

else if(b<a&&b>c||b>a&&b<c)

return b;

else

return c;

}

int Max(int a,int b,int c)

Page 34: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 34 Department of Computer Science & Engineering GEC

{

if(a>b&&a>c)

return a;

else if(b>a&&b>c)

return b;

else

return c;

}

display(struct node *t)

{

if(t!=NULL)

{

display(t->add[0]);

printf("%d\t",t->data[0]);

display(t->add[1]);

if(t->data[1]!=NULL)

{

printf("%d\t",t->data[1]);

display(t->add[2]);

}

}

}

OUTPUT: 1.insert 2.display 3.exit

enter your choice: 1

enter the value to be inserted: 7

1.insert 2.display 3.exit

enter your choice: 1

enter the value to be inserted: 16

1.insert 2.display 3.exit

enter your choice: 1

enter the value to be inserted: 5

1.insert 2.display 3.exit

enter your choice: 1

enter the value to be inserted: 8

1.insert 2.display 3.exit

enter your choice: 1

enter the value to be inserted: 12

1.insert 2.display 3.exit

enter your choice: 1

Page 35: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 35 Department of Computer Science & Engineering GEC

enter the value to be inserted: 19

1.insert 2.display 3.exit

enter your choice: 2

Elements are : 5 7 8 12 16 19

1.insert 2.display 3.exit

enter your choice: 4

wrong choice...

1.insert 2.display 3.exit

enter your choice: 3

EXERCISE: 4

AIM:

To Write a C program to perform various operations on Binary Heap.

DESCRIPTION:

Binary Heaps:

Heaps (occasionally called as partially ordered trees) are a very popular data structure for

implementing priority queues.

A heap is either a min-heap or a max-heap. A min-heap supports the insert and delete-min

operations while a max-heap supports the insert and delete-max operations.

Heaps could be binary or d-ary. Binary heaps are special forms of binary trees while d-ary

heaps are a special class of general trees.

Definition: A binary heap is a complete binary tree with elements from a partially ordered set, such

that the element at every node is less than (or equal to) the element at its left child and the element at

its right child. Figure 1 shows and example of a heap.

Figure 1: An example of a heap and its array representation

Page 36: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 36 Department of Computer Science & Engineering GEC

Since a heap is a complete binary tree, the elements can be conveniently stored in an array. If

an element is at position i in the array, then the left child will be in position 2i and the right

child will be in position 2i + 1. By the same token, a non-root element at position i will have

its parent at position [i/2].

Because of its structure, a heap with height k will have between 2kand 2

k + 1 - 1 elements.

Therefore a heap with n elements will have height = [log2n].

Because of the heap property, the minimum element will always be present at the root of the

heap. Thus the find min operation will have worst-case O (1) running time.

ALGORITHM FOR INSERTIONS INTO MIN-HEAP:

Insert: To insert an element say x, into the heap with n elements, we first create a hole in position

(n+1) and see if the heap property is violated by putting x into the hole. If the heap property is not

violated, then we have found the correct position for x. Otherwise, we ``push-up'' or ``percolate-up'' x

until the heap property is restored. To do this, we slide the element that is in the hole's parent node

into the hole, thus bubbling the hole up toward the root. We continue this process until x can be

placed in the whole. See Figure 2 for an example.

Figure 2: Insertion into a heap

Page 37: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 37 Department of Computer Science & Engineering GEC

Worst case complexity of insert is O (h) where h is the height of the heap. Thus insertions are O (log

n) where n is the number of elements in the heap.

ALGORITHM FOR DELETIONS INTO MIN-HEAP:

When the minimum is deleted, a hole is created at the root level. Since the heap now has one less

element and the heap is a complete binary tree, the element in the least position is to be relocated.

This we first do by placing the last element in the hole created at the root. This will leave the heap

property possibly violated at the root level. We now ``push-down'' or ``percolate-down'' the hole at

the root until the violation of heap property is stopped. While pushing down the hole, it is important

to slide it down to the less of its two children (pushing up the latter). This is done so as not to create

another violation of heap property. See Figure 3. It is easy to see that the worst-case running time

of delete-min is O (log n) where n is the number of elements in the heap.

Figure 3: Deletemin

Page 38: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 38 Department of Computer Science & Engineering GEC

ALGORITHM FOR CREATING HEAP:

Given a set of n elements, the problem here is to create a heap of these elements.

Obvious approach is to insert the n elements, one at a time, into an initially empty heap. Since

the worst case complexity of inserts is O (log n), this approach has a worst case running time

of O ( n log n)

Another approach, purposed by Floyd in 1964, is to use a procedure called ``pushdown''

repeatedly, starting with the array consisting of the given n elements in the input-order.

o The function pushdown (first, last) assumes that the elements a[first], ..., a[last] obey

the heap property, except possibly the children of a[first]. The function pushes down

a[first] until the heap property violation is stopped.

o The following code will accomplish what is required:

For (i=n/2;i>=1;i++)

Pushdown(I,n);

Figure 4 shows an example of this for an array [5 9 4 2 1 6]. The worst case complexity of this

approach can be shown to b O (n) by virtue of the following result.

Figure 4: Creation of heap

Page 39: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 39 Department of Computer Science & Engineering GEC

Algorithm:

1.

PROGRAM:

#include<stdio.h>

#include<conio.h>

int ch,i,heap[50],n,k,left,right,target,temp,parent;

void main()

{

clrscr();

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

printf("\n[1].BUILD_HEAP\n[2].INSERT\n[3].DELETEMIN\n[4].DISPLAY\n[0].EXIT");

do

{

printf("\nChoose Operation:");

scanf("%d",&ch);

switch(ch)

{

case 1: build_heap();

display();

break;

case 2: insert();

break;

case 3: deletemin();

break;

case 4: display();

break;

}

}while(ch!=0);

}

build_heap()

Page 40: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 40 Department of Computer Science & Engineering GEC

{

printf("\nEnter No of Elements in Heap:");

scanf("%d",&n);

printf("\nEnter %d elements:\n",n);

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

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

for(i=n/2;i>0;i--)

percolate_down(i);

}

insert()

{

printf("Enter Element:");

scanf("%d",&temp);

n++;

heap[n]=temp;

printf("\nElement Inserted");

percolate_up(n);

}

deletemin()

{

if(n>0)

{

printf("\nElement Deleted Is:%d",heap[1]);

heap[1]=heap[n];

heap[n]=0;

n--;

percolate_down(1);

}

else printf("\nHeap Is Empty");

}

display()

{

Page 41: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 41 Department of Computer Science & Engineering GEC

if(n>0)

{

printf("\nThe Min-Heap is:\n");

i=1;

while(i<=n)

{

for(k=i;k<(2*i) && k<=n;k++)

printf("%d ",heap[k]);

printf("\n");

i=k;

}

}

else printf("\nHeap is Empty");

}

percolate_up(int m)

{

while(m>1)

{

parent=m/2;

if(heap[parent] > heap[m])

{

temp=heap[m];

heap[m]=heap[parent];

heap[parent]=temp;

m=parent;

}

else break;

}

}

percolate_down(int m)

{

while(2*m <= n)

Page 42: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 42 Department of Computer Science & Engineering GEC

{

left=2*m;

right=2*m+1;

if(right <=n && heap[right] < heap[left])

target=right;

else

target=left;

if(heap[target] < heap[m])

{

temp=heap[m];

heap[m]=heap[target];

heap[target]=temp;

m=target;

}

else break;

}

}

OUTPUT:

(1).

---------------HEAP OPERATIONS------------------

[1].BUILD_HEAP

[2].INSERT

[3].DELETEMIN

[4].DISPLAY

[0].EXIT

Choose Operation:1

Enter No of Elements in Heap:5

Enter 5 elements:

12

34

Page 43: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 43 Department of Computer Science & Engineering GEC

5

6

89

The Min-Heap is:

5

6 12

34 89

Choose Operation:2

Enter Element:4

Element Inserted

Choose Operation:4

The Min-Heap is:

4

6 5

34 89 12

Choose Operation:2

Enter Element:7

Element Inserted

Choose Operation:4

The Min-Heap is:

4

6 5

34 89 12 7

34 89 12 7

Page 44: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 44 Department of Computer Science & Engineering GEC

Choose Operation:3

Element Deleted Is:4

Choose Operation:4

The Min-Heap is:

5

6 7

34 89 12

Choose Operation:3

Element Deleted Is:5

Choose Operation:4

The Min-Heap is:

6

12 7

Choose Operation:0

EXERCISE: 5

AIM:

Write a C program to implement operations on graphs

Vertex insertion

Vertex deletion

Edge addition

Edge deletion

Find vertex

DESCRIPTION:

1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E)

2. Graphs can be directed, or undirected, weighted or unweighted.

Page 45: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 45 Department of Computer Science & Engineering GEC

3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1

being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has

direction – trees are special kinds of directed graphs)

4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being

connected to edge 2 does imply that edge 2 is connected to edge 1.

5. A weighted graph is graph which has a value associated with each edge. This can be a

distance, or cost, or some other numeric value associated with the edge.

ALGORITHM :

(i) VertexInsertion() { If(find(v)==-1) { Ver[n++]=v; Vetex inserted. } }

(ii) DeleteVertex() { i=n-1; v=ver[i]; ver[i]=0; // vertex deleted for(j=0;j<n;j++) { adj[i][j]=adj[j][i]=0; // deletion of edges from that vertex } n--; }

(iii) Add Edge() { If(s!=d && find(s)!=-1 && find(d)!=-1) { i=find(s); j=find(d); if(adj[i][j]==1) printf “already connected”;

Page 46: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 46 Department of Computer Science & Engineering GEC

else adj[i][j]=1; print “edge connected”; } Print “edge connection not possible”; }

(iv) DeleteEdge() {

If(s!=d && find(s)!=-1 && find(d)!=-1) { i=find(s); j=find(d); if(adj[i][j]==1) { adj[i][j]=0; print “edge deleted”; } else Print “edge not connected”;

} (v) FindVertex(char v)

{ for(int k=0;k<n;k++) { if(ver[k]==v) return k; // vertex found at index k else return -1; }

PROGRAM:

#include<stdio.h>

#include<conio.h>

int n,i,j,ad[10][10];

char ver[20];

display()

Page 47: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 47 Department of Computer Science & Engineering GEC

{

printf("\nVERTEX\tADJACENT VERTICES\n");

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

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

{

printf("%c\t",ver[i]);

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

{

if(ad[i][j]!=0)

printf("-->%c",ver[j]);

}

printf("\n");

}

}

int find(char v)

{

int k;

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

{

if(ver[k]==v)

return k;

}

return -1;

}

main()

{

char s,d,v;

int op;

n=0;

clrscr();

do

{

Page 48: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 48 Department of Computer Science & Engineering GEC

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

printf("[1].INSERT VERTEX\n[2].DELETE VERTEX\n[3].ADD AN EDGE\n

[4].DELETE AN EDGE\n[5].FIND VERTEX\n[6].DISPLAY\n[0].EXIT");

printf("\n\nChoose an Operation:");

scanf("%d",&op);

switch(op)

{

case 1:printf("\nEnter Vertex:");

fflush(stdin);

scanf("%c",&v);

if(find(v)!=-1)

printf("\nVERTEX already exists");

else

{

ver[n++]=v;

printf("\nVERTEX INSERTED");

}

break;

case 2:if(n==0) printf("\nGRAPH IS EMPTY");

else

{

i=n-1;

v=ver[n-1];

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

{

ver[i]=0;

ad[i][j]=ad[j][i]=0;

}

n--;

printf("\nVERTEX DELETED Is :%c",v);

}

break;

Page 49: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 49 Department of Computer Science & Engineering GEC

case 3:if(n==0) printf("\nGRAPH IS EMPTY");

else

{

printf("\nEnter Source Vertex:");

fflush(stdin);

scanf("%c",&s);

printf("\nEnter Destination Vertex:");

fflush(stdin);

scanf("%c",&d);

if(s!=d && find(s)!=-1 && find(d)!=-1)

{

i=find(s);

j=find(d);

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

{

ad[i][j]=1;

printf("\nEDGE INSERTED\n");

}

else printf("\nAlready they are connected by an EDGE");

}

else printf("\nEDGE Is Not Connected\n");

}

break;

case 4:if(n==0) printf("\nGRAPH IS EMPTY");

else

{

printf("\nEnter Source Vertex:");

fflush(stdin);

scanf("%c",&s);

printf("\nEnter Destination Vertex:");

fflush(stdin);

scanf("%c",&d);

Page 50: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 50 Department of Computer Science & Engineering GEC

i=find(s);

j=find(d);

if(ad[i][j]!=1)

printf("\nThere is No edge Connecting them");

else

{

ad[i][j]=0;

printf("\nEDGE DELETED\n");

}

}

break;

case 5:if(n==0) printf("\nGRAPH IS EMPTY");

else

{

printf("\nEnter Vertex:");

fflush(stdin);

scanf("%c",&v);

if(find(v)!=-1)

printf("\nVERTEX FOUND");

else

printf("\nVERTEX NOT FOUND");

}

break;

case 6:if(n==0) printf("\nGRAPH IS EMPTY");

else display();

break;

}

}while(op!=0);

}

OUTPUT:

---------------------OPERATIONS-----------------------

Page 51: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 51 Department of Computer Science & Engineering GEC

[1].INSERT VERTEX

[2].DELETE VERTEX

[3].ADD AN EDGE

[4].DELETE AN EDGE

[5].FIND VERTEX

[6].DISPLAY

[0].EXIT

Choose an Operation:1

Enter Vertex: A

VERTEX INSERTED

Choose an Operation:1

Enter Vertex:B

VERTEX INSERTED

Choose an Operation:1

Enter Vertex:C

VERTEX INSERTED

Choose an Operation:3

Enter Source Vertex:A

Enter Destination Vertex:B

EDGE INSERTED

Choose an Operation:3

Enter Source Vertex:B

Enter Destination Vertex:C

EDGE INSERTED

Choose an Operation:4

Enter Source Vertex:C

Enter Destination Vertex:B

Page 52: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 52 Department of Computer Science & Engineering GEC

There is No edge Connecting them

Choose an Operation:6

VERTEX ADJACENT VERTICES

------------------------------------------------

A -->B

B -->C

C

Choose an Operation:3

Enter Source Vertex: A

Enter Destination Vertex:C

EDGE INSERTED

Choose an Operation:6

VERTEX ADJACENT VERTICES

------------------------------------------------

A -->B-->C

B -->C

C

Choose an Operation:4

Enter Source Vertex:A

Enter Destination Vertex:C

EDGE DELETED

Choose an Operation:6

VERTEX ADJACENT VERTICES

------------------------------------------------

A -->B

B -->C

Page 53: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 53 Department of Computer Science & Engineering GEC

C

Choose an Operation:2

VERTEX DELETED Is :C

Choose an Operation:5

Enter Vertex:E

VERTEX NOT FOUND

Choose an Operation:5

Enter Vertex:B

VERTEX FOUND

Choose an Operation:0

EXERCISE: 6

AIM:

Write a C program to implement Depth First Search for a graph non recursively.

DESCRIPTION:

1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E)

2. Graphs can be directed, or undirected, weighted or unweighted.

3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1

being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has

direction – trees are special kinds of directed graphs).

4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being

connected to edge 2 does imply that edge 2 is connected to edge 1.

5. A weighted graph is graph which has a value associated with each edge. This can be a

distance, or cost, or some other numeric value associated with the edge.

ALGORITHM FOR DEPTH FIRST SEARCH AND TRAVERSAL:

A depth first search of a graph differs from a breadth first search in that the exploration of a

vertex v is suspended as soon as a new vertex is reached. At this time of exploration of the new

vertex u begins. When this new vertex has been explored, the exploration of v continues. The search

terminates when all reached vertices have been fully explored. The search process is best described

recursively in the following algorithm.

Page 54: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 54 Department of Computer Science & Engineering GEC

Algorithm DFS(v)

{

// Given an undirected(directed) graph G=(V,E) with n vertices and an

//array visited [] initially set to zero, this algorithm visits all vertices reachable

//from v. G and visited[] are global.

if(V==NULL)

print “graph empty”

else

{

while(stack is not empty)

{

V1=pop(v);

if(visited[V1]==false) /*if V1 has not yet visited*/

visited[V1]=true; /* visit V1*/

for(each w adjacent to V1)

{

if(visited[w]==false && inStack(w)==0)

push(w);

}

}//while

}//else

}

PROGRAM:

#include<stdio.h>

#include<conio.h>

int am[10][10],n,v,visited[10],stk[10];

int i,j,top=-1;

void main()

{

clrscr();

printf("Enter Number of Vertices:");

scanf("%d",&n);

printf("\nEnter Adjacency Matrix:");

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

{

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

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

visited[i]=0;

}

printf("Enter Starting Node:");

scanf("%d",&v);

dfs(v);

}

Page 55: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 55 Department of Computer Science & Engineering GEC

dfs(int st)

{

top++;

stk[top]=st;

while(top>=0)

{

v=stk[top];

top--;

if(visited[v]==0)

{

visited[v]=1;

printf("-->%d",v);

}

for(i=n;i>=1;i--)

{

if(am[v][i]==1 && visited[i]==0)

{

if(instack(i)==0)

{

top++;

stk[top]=i;

}

}

}

}

}

int instack(int n)

{

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

{

if(stk[j]==n)

return 1;

}

return 0;

}

OUTPUT:

Enter Number of Vertices:5

Enter Adjacency Matrix:

0 1 1 0 0

1 0 1 1 0

1 1 0 0 0

0 1 0 0 1

0 0 0 1 0

Page 56: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 56 Department of Computer Science & Engineering GEC

Enter Starting Node:1

-->1-->2-->4-->5-->3

EXERCISE: 7

AIM:

Write a C program to implement Breadth First Search for a graph non recursively.

DESCRIPTION:

1. A graph can be thought of a collection of vertices(V) and edges(E), so we write, G = (V, E)

2. Graphs can be directed, or undirected, weighted or unweighted.

3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge

1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has

direction – trees are special kinds of directed graphs).

4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1

being connected to edge 2 does imply that edge 2 is connected to edge 1.

5. A weighted graph is graph which has a value associated with each edge. This can be a

distance, or cost, or some other numeric value associated with the edge.

ALGORITHM FOR BREADTH FIRST SEARCH AND TRAVERSAL:

In Breadth first search we start at vertex v and mark it as having been reached (visited) the

vertex v is at this time said to be unexplored. A vertex is said to have been explored by an algorithm

when the algorithm has visited all vertices adjacent from it. All unvisited vertices adjacent from v are

visited next. These are new unexplored vertices. Vertex v has now been explored. The newly visited

vertices have not been explored and or put on to the end of a list of unexplored list of vertices. The

first vertex on this list is the next to be explored. Exploration continues until no unexplored vertex is

left. The list of unexplored vertices operates as a queue and can be represented using any of the

standard queue representations.

Algorithm BFS(v)

{

//A breadth first search of G is carried out beginning at vertex v. For

//any node v, visited[v]=1 if I has already been visited. The graph G

//and array visited are global; visited[] is initialized to zero.

Page 57: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 57 Department of Computer Science & Engineering GEC

If(v==NULL)

Print “Graph Empty”;

end if.

else

{

enque(v)

while(queue is not empty)

{

V1=dequeue;

If(visited[v1]==false)

visited[v1]=true;

for(each w adjacent to v1)

{

If(visited[w]==false && inqueue(w)==0)

enqueue(w);

}

}//while

}

}

PROGRAM:

#include<stdio.h>

#include<conio.h>

int am[10][10],n,v,visited[10],q[20],i,j,front=0,rear=0;

void main()

{

clrscr();

printf("Enter Number of Vertices:");

scanf("%d",&n);

printf("\nEnter Adjacency Matrix:");

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

{

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

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

visited[i]=0;

}

printf("Enter Starting Node:");

Page 58: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 58 Department of Computer Science & Engineering GEC

scanf("%d",&v);

bfs(v);

getch();

}

bfs(int st)

{

q[rear]=st;

rear++;

while(front<rear)

{

v=q[front];

front++;

if(visited[v]==0)

{

visited[v]=1;

printf("-->%d",v);

}

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

{

if(am[v][i]==1 && visited[i]==0)

{

if(inqueue(i)==0)

{

q[rear]=i;

rear++;

}

}

}

}

}

int inqueue(int n)

{

Page 59: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 59 Department of Computer Science & Engineering GEC

for(j=front;j<=rear;j++)

{

if(q[j]==n)

return 1;

}

return 0;

}

OUTPUT:

Enter Number of Vertices:5

Enter Adjacency Matrix:

0 1 1 0 0

1 0 1 1 0

1 1 0 0 0

0 1 0 0 1

0 0 0 1 0

Enter Starting Node:1

-->1-->2-->3-->4-->5

EXERCISE: 8

AIM:

Write a C program to implement Prim’s algorithm to generate a min-cost spanning tree.

DESCRIPTION:

Minimum-Cost Spanning Trees:

Let G = (V, E) be a connected graph in which each edge (u, v) Є E has an associated cost C(u, v).

A Spanning Tree for G is a sub-graph of G that it is a free tree connecting all vertices in V. The

cost of a spanning tree is the sum of costs on its edges.

An MST of G is a spanning tree of G having a minimum cost.

See Figure 1 for several examples.

Page 60: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 60 Department of Computer Science & Engineering GEC

Figure 1: Spanning trees in a connected graph

PRIM'S ALGORITHM:

Initially graph G=(V,E) ,spanning tree T=(V1,E1) where V1={u} and E1={ Ø }

{

while (number of edges are less than or equal to (n-1))

{

, let (u, v) be the lowest cost edge

such that uЄ V1 and vЄ V – V1;

E1= E1 {(u, v)}

V1 = V1 {v}

if no such edge

break;

}

}

See Figure 2 for an example.

Prim’s can be computed in O(n2) time.

Implementation of Prim's Algorithm:

Page 61: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 61 Department of Computer Science & Engineering GEC

Use two arrays, closest and lowcost.

For i Є V - U, closest[i] gives the vertex in U that is closest to i

For i Є V - U, lowcost[i] gives the cost of the edge (i, closest(i))

PROGRAM:

#include<stdio.h>

#include<conio.h>

int a,b,n,i,j,k,ne;

int min,mincost=0,cost[10][10],V[10];

void main()

{

clrscr();

printf("\n Enter the number of nodes:");

scanf("%d",&n);

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

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

{

Figure 2: Illustration of Prim's algorithm

Page 62: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 62 Department of Computer Science & Engineering GEC

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

{

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

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

cost[i][j]=999;

}

}

V[1]=1;

ne=1;

while(ne<n)

{

min=999;

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

{

if(inset(i)==1)

{

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

{

if(inset(j)==0 && cost[i][j]<min)

{

min=cost[i][j];

a=i;

b=j;

}

}

}

}

printf("\n Edge %d:(%d %d) cost:%d",ne,a,b,min);

ne++;

V[ne]=b;

mincost=mincost+min;

cost[a][b]=cost[b][a]=999;

Page 63: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 63 Department of Computer Science & Engineering GEC

}

printf("\n Minimun cost=%d",mincost);

getch();

}

int inset(int k)

{

int m=1;

while(m<=ne)

{

if(V[m]==k)

return 1;

else

m++;

}

return 0;

}

OUTPUT:

Enter the number of nodes:6

Enter the adjacency matrix:

0 6 1 5 999 999

6 0 5 999 3 999

1 5 0 5 999 4

5 999 5 0 999 2

999 3 999 999 0 6

999 999 4 2 6 0

Edge 1:(1 3) cost:1

Edge 2:(3 6) cost:4

Edge 3:(6 4) cost:2

Edge 4:(3 2) cost:5

Edge 5:(2 5) cost:3

Minimun cost=15

Page 64: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 64 Department of Computer Science & Engineering GEC

EXERCISE: 9

AIM:

Write a C program to implement Kruskal’s algorithm to generate a min-cost spanning tree.

DESCRIPTION:

Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning

tree for a connected weighted graph.

This means it finds a subset of the edges that forms a tree that includes every vertex, where the

total weight of all the edges in the tree is minimized.

If the graph is not connected, then it finds a minimum spanning forest (a minimum spanning

tree for each connected component).

Complexity is O(elog e) where e is the number of edges. Can be made even more efficient by a

proper choice of data structures.

KRUSKAL'S ALGORITHM:

Let G = (V, E) be the given graph, with | V| = n

{

Start with a graph T = (V,Ø) consisting of only the vertices of G and no edges;

/* This can be viewed as n connected components, each vertex being one connected

component */

}

PROGRAM: #include<stdio.h>

#include<conio.h>

int i,j,k,u,v,n,ne=1,a,b;

int min,mincost=0,cost[9][9],set[9];

void main()

{

clrscr();

printf("\n\tImplementation of Kruskal's algorithm\n");

printf("\nEnter the no. of vertices:");

scanf("%d",&n);

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

Page 65: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 65 Department of Computer Science & Engineering GEC

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

{

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

{

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

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

cost[i][j]=999;

}

}

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

set[i]=i;

printf("The edges of Minimum Cost Spanning Tree are\n");

while(ne<n)

{

min=999;

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

{

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

{

if(cost[i][j] < min)

{

min=cost[i][j];

a=i;

b=j;

}

}

}

u=find(a);

v=find(b);

if(u!=v)

{

uni(u,v);

printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);

mincost=mincost+min;

}

cost[a][b]=cost[b][a]=999;

}

printf("\n\tMinimum cost = %d\n",mincost);

getch();

}

int find(int i)

{

i=set[i];

return i;

}

int uni(int i,int j)

{

Page 66: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 66 Department of Computer Science & Engineering GEC

set[j]=i;

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

{

if(set[k]==j)

set[k]=i;

}

}

OUTPUT:

Implementation of Kruskal's algorithm

Enter the no. of vertices:6

Enter the cost adjacency matrix:

0 6 1 5 999 999

6 0 5 999 3 999

1 5 0 5 999 4

5 999 5 0 999 2

999 3 999 999 0 6

999 999 4 2 6 0

The edges of Minimum Cost Spanning Tree are

1 edge (1,3) =1

2 edge (4,6) =2

3 edge (2,5) =3

4 edge (3,6) =4

5 edge (2,3) =5

Minimum cost = 15

EXERCISE: 10

AIM:

Write a C program to implement Dijkstra’s algorithm to find shortest path in the graph.

DESCRIPTION:

Single Source Shortest Paths Problem: Dijkstra's Algorithm:

Greedy algorithm

It works by maintaining a set S of ``special'' vertices whose shortest distance from the source is

already known. At each step, a ``non-special'' vertex is absorbed into S.

The absorption of an element of V - S into S is done by a greedy strategy.

With adjacency matrix representation, the running time is O(n2)

The following provides the steps of the algorithm.

Page 67: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 67 Department of Computer Science & Engineering GEC

Example: Consider the digraph in Figure 1.

Figure 1: A digraph example for Dijkstra's algorithm

Initially:S = {1} D[2] = 10 D[3] = ∞ D[4] = 30 D[5] = 100

Iteration 1 Select w = 2, so that S = {1, 2}

D[3] = min( , D[2] + C[2, 3]) = 60 (7.2)

D[4] = min(30, D[2] + C[2, 4]) = 30 (7.3)

D[5] = min(100, D[2] + C[2, 5]) = 100

Iteration 2

Select w = 4, so that S = {1, 2, 4}

D[3] = min(60, D[4] + C[4, 3]) = 50 (7.4)

D[5] = min(100, D[4] + C[4, 5]) = 90

Iteration 3 Select w = 3, so that S = {1, 2, 4, 3}

D[5] = min(90, D[3] + C[3, 5]) = 60

Iteration 4 Select w = 5, so that S = {1, 2, 4, 3, 5}

D[2] = 10 (7.5)

D[3] = 50 (7.6)

D[4] = 30 (7.7)

D[5] = 60

PROGRAM: #include<stdio.h>

#include<conio.h>

Page 68: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 68 Department of Computer Science & Engineering GEC

int s,u,n,i,j,cost[10][10],d[10],found[10],pre[10];

void shortest_path()

{

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

{

found[i]=0;

d[i]=cost[s][i];

pre[i]=s;

}

found[s]=1;

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

{

u=choose();

found[u]=1;

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

{

if(!found[j])

{

if(d[u]+cost[u][j] < d[j])

{

d[j]=d[u]+cost[u][j];

pre[j]=u;

}

}

}

}

}

int choose()

{

int i,j,min=999,minpos=-1;

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

{

if(d[i]<min && !found[i])

{

min=d[i];

minpos=i;

}

}

return minpos;

}

path(int i)

{

printf("%d",i);

while(i!=s)

{

i=pre[i];

Page 69: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 69 Department of Computer Science & Engineering GEC

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

}

}

void main()

{

clrscr();

printf("\nEnter Number of Nodes:");

scanf("%d",&n);

printf("\nEnter Cost Matrix:\n");

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

{

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

{

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

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

cost[i][j]=999;

}

}

printf("\nEnter Source Node:");

scanf("%d",&s);

shortest_path();

printf("\nNODE\tSHORTEST PATH\t\tPATH COST\n");

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

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

{

if(i!=s && d[i]!=999)

{

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

path(i);

printf("\t\tMinimum Cost :%d\n",d[i]);

}

}

getch();

}

OUTPUT:

Enter Number of Nodes:5

Enter Cost Matrix:

0 10 999 30 100

0 0 50 999 999

999 999 0 999 10

999 999 20 999 60

999 999 999 999 0

Enter Source Node:1

Page 70: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 70 Department of Computer Science & Engineering GEC

NODE SHORTEST PATH PATH COST

------------------------------------------------------

2 2<--1 Minimum Cost :10

3 3<--4<--1 Minimum Cost :50

4 4<--1 Minimum Cost :30

5 5<--3<--4<--1 Minimum Cost :60

EXERCISE: 11

AIM:

Write a C program to implement pattern matching using Boyer-Moore algorithm.

DESCRIPTION:

Boyer Moore Pattern Matching Algorithm:

The Boyer-Moore pattern matching algorithm is based on two techniques.

1. The looking-glass technique: find P in T by moving backwards through P, starting at

its end.

2. The character-jump technique: when a mismatch occurs at T[i] == xth character in

pattern P[j] is not the same as T[i]. There are 3 possible cases, tried in order.

Case 1

• If P contains x somewhere, then try to shift P right to align the last occurrence of x in P with T[i].

x aT

i

b aP

j

x c

x aT

inew

b aP

jnew

x c

and move i and j right, soj at end

Page 71: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 71 Department of Computer Science & Engineering GEC

Case 2

• If P contains x somewhere, but a shift right to the last occurrence is not possible, thenshift P right by 1 character to T[i+1].

a xT

i

a xP

j

c w

a xT

inew

a xP

jnew

c w

and move i and j right, soj at end

x

x is after j position

x

Case 3

• If cases and do not apply, then shift P to align P[ ] with T[i+

x aT

i

b aP

j

d c

x aT

inew

b aP

jnew

d c

and move i and j right, soj at end

No x in P

Page 72: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 72 Department of Computer Science & Engineering GEC

Boyer-Moore Example 1

1

a p a t t e r n m a t c h i n g a l g o r i t h m

r i t h m

r i t h m

r i t h m

r i t h m

r i t h m

r i t h m

r i t h m

2

3

4

5

6

7891011

T:

P:

Boyer-Moore Example 2

1

a b a c a a b a d c a b a c a b a a b b

234

5

6

7

891012

a b a c a b

a b a c a b

a b a c a b

a b a c a b

a b a c a b

a b a c a b

1113

-1354L(x)

dcbax

T:

P:

Last occurrence function L ( ): Boyer-Moore’s algorithm preprocesses the pattern P and the

alphabet A to build a last occurrence function L ().

L() maps all the letters in A to integers,

L(x) is defined as: // x is a letter in Athe largest index i such that P[i] == x, or -1 if no such

index exists

In Boyer-Moore code, L() is calculated when the pattern P is read in.

Page 73: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 73 Department of Computer Science & Engineering GEC

L() Example

• A = {a, b, c, d}

• P: "abacab"

-1354L(x)

dcbax

a b a c a bP

L() stores indexes into P[]

ANALYSIS:

Boyer-Moore worst case running time is O(nm + A).

But, Boyer-Moore is fast when the alphabet (A) is large, slow when the alphabet is small. e.g.

good for English text, poor for binary.

Boyer-Moore is significantly faster than brute force for searching English text.

ALGORITHM: Algorithm BMP (T, P, S)

{

L lastOccurenceFunction(P, S )

im -1

jm -1

while(n<i)

{

ifT[i]= P[j]

{

if j=0

return i { match at i }

else

ii-1

jj-1

}

else

{

//character-jump

ii+ m – min(j, 1 + L[T[i]])

jm -1

}

return -1{ no match }

}

Page 74: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 74 Department of Computer Science & Engineering GEC

PROGRAM: #include<stdio.h> #include<conio.h> #include<string.h> char t[30],p[15]; int last[15]; main() { int pos,i; clrscr(); printf("\n enter text: "); scanf("%s",t); printf("\n enter pattern: "); scanf("%s",p); /* calculate last function */ for(i=0;p[i]!='\0';i++) last[p[i]]=i; pos=pattern_match(); if(pos==-1) printf("\n given pattern is not matched"); else printf("\n pattern is matched at : %d",pos+1); getch(); } int pattern_match() { int n,m,i,j; n=strlen(t); m=strlen(p); i=m-1; j=m-1; while(i<n) { if(t[i]==p[j]) { if(j==0) return i; else

Page 75: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 75 Department of Computer Science & Engineering GEC

{ i--; j--; } } else { i=i+m-min(j,1+last[t[i]]); j=m-1; } } return(-1); } int min(int x,int y) { if(x<y) return x; else return y; }

OUTPUT:

enter text: abcbaabbcabc

enter pattern: bcab

pattern is matched at : 8

enter text: aabbabcbba

enter pattern: bbaa

given pattern is not matched

Page 76: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 76 Department of Computer Science & Engineering GEC

EXERCISE: 12 AIM:

Write a C program to implement Knuth-Morris-Pratt algorithm for pattern matching.

DESCRIPTION:

KMP Failure Function

• Knuth-Morris-Pratt’s algorithmpreprocesses the pattern to findmatches of prefixes of thepattern with the pattern itself

• The failure function F(j) isdefined as the size of the largestprefix of P[0..j] that is also asuffix of P[1..j]

• Knuth-Morris-Pratt’s algorithmmodifies the brute-forcealgorithm so that if a mismatchoccurs at P[j] T[i] we set j

F(j - 1)

j 0 1 2 3 4 5

P[j] a b a a b a

F(j) 0 0 1 1 2 3

x

j

. . a b a a b . . . . .

a b a a b a

F(j-1)

a b a a b a

ALGORITHM:

The KMP Algorithm

• The failure function can berepresented by an array and canbe computed in O(m) time

• At each iteration of the while-loop, either

– i increases by one, or

– the shift amount i - j increasesby at least one (observe that F(j

- 1) < j)

• Hence, there are no more than2n iterations of the while-loop

• Thus, KMP’s algorithm runs inoptimal time O(m + n)

Algorithm KMPMatch(T, P)

F failureFunction(P)i 0j 0while i < n

if T[i] = P[j]if j = m - 1

return i - j { match }else

i i + 1j j + 1

elseif j > 0

j F[j - 1]else

i i + 1return -1 { no match }

Page 77: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 77 Department of Computer Science & Engineering GEC

Computing the Failure Function

• The failure function can berepresented by an array and can becomputed in O(m) time

• The construction is similar to theKMP algorithm itself

• At each iteration of the while-loop,either

– i increases by one, or

– the shift amount i - j increases byat least one (observe that F(j - 1)

< j)

• Hence, there are no more than 2m

iterations of the while-loop

Algorithm failureFunction(P)

F[0] 0i 1j 0while i < m

if P[i] = P[j]{we have matched j + 1

chars}F[i] j + 1i i + 1j j + 1

else if j > 0 then{use failure function to

shift P}j F[j - 1]

elseF[i] 0 { no match }i i + 1

Example

1

a b a c a a b a c a b a c a b a a b b

7

8

19181715

a b a c a b

1614

13

2 3 4 5 6

9

a b a c a b

a b a c a b

a b a c a b

a b a c a b

10 11 12

c

j 0 1 2 3 4 5

P[j] a b a c a b

F(j) 0 0 1 0 1 2

ALGORITHM:

int KMPmatch(T,P)

{

FailureFunction(P);

n=strlen(T);

m=strlen(P);

i=0;

j=0;

while(i<n)

{

if(p[j]==t[i])

{

if(j==m-1)

return i-(m-1);

else

{

i++;

j++;

Page 78: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 78 Department of Computer Science & Engineering GEC

}

}

else if(j>0)

j=f[j-1];

else

i++;

}

return -1;

}

PROGRAM: #include<stdio.h>

#include<conio.h>

#include<string.h>

char t[30],p[15];

int f[15],i,j,n,m;

main()

{

int pos;

clrscr();

printf("\n enter text: ");

scanf("%s",t);

printf("\n enter pattern: ");

scanf("%s",p);

m=strlen(p);

n=strlen(t);

failurefunction();

pos=KMPmatch();

if(pos==-1)

printf("\n Pattern: %s Not Found",p);

else

printf("\n Pattern is matched at : %d",pos+1);

getch();

}

int KMPmatch()

{

i=0;

j=0;

while(i<n)

{

if(p[j]==t[i])

{

if(j==m-1)

return i-(m-1);

else

{

i++;

j++;

Page 79: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 79 Department of Computer Science & Engineering GEC

}

}

else if(j>0)

j=f[j-1];

else

i++;

}

return -1;

}

failurefunction()

{

i=1;

j=0;

f[0]=0;

while(i<m)

{

if(p[j]==p[i])

{

f[i]=j+1;

i++;

j++;

}

else if(j>0)

j=f[j-1];

else

{

f[i]=0;

i++;

}

}

}

OUTPUT: Case 1:

enter text: abcaabba

enter pattern: abba

Pattern is matched at : 5

Case 2:

Enter text: advanced data structures

Enter pattern : ads

Pattern is not matched.

Page 80: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 80 Department of Computer Science & Engineering GEC

ADDITIONAL PROGRAMS

EXERCISE: 1

AIM:

a) Write a C program to implement Floyd’s algorithm to find the shortest path in the given graph.

DESCRIPTION: This algorithm is designed to find the least-expensive paths between all the vertices in a graph. It

does this by operating on a matrix representing the costs of edges between vertices.

Before we invoke Floyd's algorithm we must build a matrix, usually in a two-dimensional

array.

Floyd’s algorithm uses Dynamic Programming design strategy.

If there are n vertices in our graph, our matrix will be nxn. Each row in the matrix represents a

"starting" vertex in the graph while each column in the matrix represents an "ending" point in

the graph.

A representation: a weight/cost matrix where

C(i,j)=0 if i=j.

C(i,j)=infinity if there is no edge between i and j.

C(i,j)=“weight of edge”

Recursive Definition:

Case 1:

A shortest path from vi to vj restricted to using only vertices from {v1,v2,…,vk} as

intermediate vertices does not use vk. Then D(k)

[i,j]= D(k-1)

[i,j].

Case 2:

A shortest path from vi to vj restricted to using only vertices from {v1,v2,…,vk} as

intermediate vertices does use vk. Then D(k)

[i,j]= D(k-1)

[i,k]+ D(k-1)

[k,j].

Page 81: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 81 Department of Computer Science & Engineering GEC

FLOYD’S ALGORITHM: // Floyd Computes shortest distance between all pairs of nodes, and saves P to enable finding shortest

paths

1. D0 W // initialize D array to W [ ]

2. P 0 // initialize P array to [0]

3. for k 1 to n

4. do for i 1 to n

5. do for j 1 to n

6. if (Dk-1

[ i, j ] > Dk-1

[ i, k ] + Dk-1

[ k, j ] )

7. then Dk[ i, j ] D

k-1 [ i, k ] + D

k-1 [ k, j ]

8. P[ i, j ] k;

9. else Dk[ i, j ] D

k-1 [ i, j ]

It is clear that Floyd's algorithm takes n3 time where as Dijkstra’s algorithm takes n

2 time. It is

important to note, however, that for dense graphs (i.e. graphs with many edges) Floyd's algorithm

is as good as or better than Dijkstra's algorithm.

PROGRAM: #include<stdio.h>

#include<conio.h>

#define infinity 999

void main()

{

int i,j,k,path[10][10],cost[10][10],a[10][10],n;

clrscr();

printf("\n enter no of vertices: ");

scanf("%d",&n);

printf("\n enter cost adjacency matrix ( -1 for infite edge and 0 for (i,i) )...");

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

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

{

printf("\n enter a[%d][%d]: ",i,j);

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

if(cost[i][j]==-1)

{

cost[i][j]=infinity;

}

a[i][j]=cost[i][j];

path[i][j]=-1;

}

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

{

printf("\n A%d matrix is...\n",k);

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

{

Page 82: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 82 Department of Computer Science & Engineering GEC

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

if(a[i][j]>a[i][k]+a[k][j])

{

a[i][j]=a[i][k]+a[k][j];

path[i][j]=k;

}

printf(" %d\t",a[i][j]);

}

printf("\n");

} }

printf("\n path matrix is...\n");

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

{

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

printf(" %d\t",path[i][j]);

printf("\n");

} getch();

}

OUTPUT:

Enter no of vertices:3

enter cost matrix(-1 for infinity) && (0 for (i,i))

enter a[1][1]: 0

enter a[1][2]: 1

enter a[1][3]: 1

enter a[2][1]: 0

enter a[2][2]: 1

enter a[2][3]: 0

enter a[3][1]: 1

enter a[3][2]: 0

enter a[3][3]: 1

A1 matrix is

0 1 1

0 1 0

1 0 1

path matrix.....

-1 -1 -1

-1 -1 -1

-1 -1 -1

Page 83: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 83 Department of Computer Science & Engineering GEC

AIM:

b) Write a C program to implement Warshall’s algorithm to find the shortest path in the given

graph.

DESCRIPTION:

Warshall's algorithm is an efficient method for computing the transitive closure of a relation.

Warshall's algorithm takes as input the matrix MR representing the relation R and outputs the matrix

MR* of the relation R* the transitive closure of R.

The input to this algorithm is an adjacency matrix, which has 1s for any row-column pair if there

exists an edge between them. What we'll be doing here is -- checking out for every vertex, the

incoming and outgoing links.

If there exist both incoming and outgoing links for a particular vertex, we will put a 1 for the row-

column pair formed by them in the adjacency matrix.

Given the adjacency matrix C of any digraph C = (v,E), the matrix A is called the transitive closure

of C.

A[i, j] = 1 if there is a path of length one or more from vertex i to vertex j

= 0 Otherwise

Warshall's algorithm predates Floyd's algorithm and simple uses the following formula in the kth

passes of Floyd's algorithm:

Ak[i, j] = Ak - 1[i, j] (Ak - 1[i, k] Ak - 1[k, j])

where the matrix elements are treated as boolean values 0 or 1 and the

symbols and denote ``logical or'' and ``logical and'' respectively. It is easy to see that

Warshall's algorithm has a worst case complexity of O(n3) where n is the number of vertices of

the graph.

Page 84: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 84 Department of Computer Science & Engineering GEC

WARSHALL ’S ALGORITHM:

Step-1: Copy the Adjacency matrix into another matrix called the Path matrix

Step-2: Find in the Path matrix for every element in the Graph, the incoming and outgoing edges

Step-3: For every such pair of incoming and outgoing edges put a 1 in the Path matrix

It is clear that Warshall's algorithm also takes n3 time to compute and this algorithm also follows

Dynamic Programming design strategy.

Example:

The matrix MR below is the matrix representation for a relation R. Find the matrix

representation MR* of R*, the transitive closure of R.

Solution:

We know that W0=MR.

To compute W1 we notice that in the first column of W0 there are 1’s in rows 1 and 4. Thus, we

replace rows 1 and 4 with the OR of themselves and row 1.

We obtain

To compute W2 we notice that in the second column of W1 there is a 1 in row 3. Thus, we replace

row 3 with the OR of rows 3 and 2, obtaining.

Page 85: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 85 Department of Computer Science & Engineering GEC

To compute W3 we notice that in the third column of W2 there is a 1 in every row. Thus, we

replace each row with the OR of itself and row 3, obtaining.

To compute W4 we notice that in the fourth column of W3 there is a 1 in every row. Thus, we

replace each row with the OR of itself and row 4, obtaining.

Page 86: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 86 Department of Computer Science & Engineering GEC

PROGRAM:

/*bwarshals*/

#include<stdio.h>

#include<conio.h>

void main()

{

int i,j,k,n,a[10][10];

clrscr();

printf("\n enter no.of vertices:");

scanf("%d",&n);

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

{

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

{

printf("enter %d-%d:",i,j);

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

}

}

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

{

printf("\n A %d matrix is.....\n",k);

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

{

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

{

a[i][j]=a[i][j]||a[i][k]&&a[k][j];

printf("%d\t",a[i][j]);

}

printf("\n");

getch();

}

}

}

Page 87: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 87 Department of Computer Science & Engineering GEC

OUTPUT:

enter no of vertices: 4

enter a[1][1]: 0

enter a[1][2]: 1

enter a[1][3]: 1

enter a[1][4]: 0

enter a[2][1]: 0

enter a[2][2]: 0

enter a[2][3]: 1

enter a[2][4]: 1

enter a[3][1]: 0

enter a[3][2]: 0

enter a[3][3]: 0

enter a[3][4]: 1

enter a[4][1]: 1

enter a[4][2]: 0

enter a[4][3]: 0

enter a[4][4]: 0

Page 88: GUDLAVALLERU ENGINEERING COLLEGE Seshadri Rao …gecgudlavalleru.ac.in/cse/pdf/manuals/Advanced-Data-Structures-Lab... · III B.Tech ADVANCED DATA STRUTURES LAB ... GUDLAVALLERU ENGINEERING

III B.Tech ADVANCED DATA STRUTURES LAB

P a g e | 88 Department of Computer Science & Engineering GEC

A1 matrix is

0 1 1 0

0 1 1 1

0 1 1 1

1 1 1 1

A2 matrix is

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1

A3 matrix is

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1

A4 matrix is

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1