0% found this document useful (0 votes)
50 views66 pages

Ee2209 - Data Structures and Algorithms LTP 0 0 3 List of Experiments

The document describes a laboratory course on data structures and algorithms. It contains: 1. A list of 15 experiments covering topics like linked lists, trees, graphs, sorting and searching algorithms. 2. The contents page listing the experiments and their page numbers. 3. A sample experiment on implementing a singly linked list with algorithms for create, insert, delete and view operations and a C program implementing the list. The document provides details of the experiments to be performed in the lab course on basic and common data structures and algorithms.

Uploaded by

Pallavi Bharti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views66 pages

Ee2209 - Data Structures and Algorithms LTP 0 0 3 List of Experiments

The document describes a laboratory course on data structures and algorithms. It contains: 1. A list of 15 experiments covering topics like linked lists, trees, graphs, sorting and searching algorithms. 2. The contents page listing the experiments and their page numbers. 3. A sample experiment on implementing a singly linked list with algorithms for create, insert, delete and view operations and a C program implementing the list. The document provides details of the experiments to be performed in the lab course on basic and common data structures and algorithms.

Uploaded by

Pallavi Bharti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

III SEM EEE EE2209-Data Structures and Algorithms

EE2209 – DATA STRUCTURES AND ALGORITHMS

LTP
003

LIST OF EXPERIMENTS:

1. a Singly Linked List

om
b Doubly Linked List
2. Polynomial Addition
3. Infix to Postfix Expression
4. Binary Tree Traversal

.c
5. Circular Queue - Producer Consumer problem
6. Binary Search Tree

ul
7. AVL Tree
8. Queue using binary heaping
9. Hashing Techniques
pa
10. Topological Sorting
11. Dijkstra’s Algorithm
jin
12. Prim’s Algorithm
13. Backtracking Algorithm – Knapsack Problem
14. Branch and Bound Algorithm- Travelling Salesman Problem
.re

15. Randomized Algorithm


w
w
w

2
III SEM EEE EE2209-Data Structures and Algorithms

M.A.M COLLEGE OF ENGINEERING

EE2209 DATA STRUCTURES AND ALGORITHMS LAB

DEGREE / BRANCH: B.E/EEE YEAR / SEM: II/III

TABLE OF CONTENTS
Ex. No TITLE Page No

om
1.a Singly Linked List 04

1.b Doubly Linked List 09

.c
2. Polynomial Addition 14

3. Infix to Postfix Expression 18

ul
4. Binary Tree Traversal 21
pa
5. Circular Queue - Producer Consumer problem 26

6. Binary Search Tree 29


jin

7. AVL Tree 36

8. Queue using binary heaping 42


.re

9. Hashing Techniques 46

10. Topological Sorting 48


w

11 Dijkstra’s Algorithm 52
w

12. Prim’s Algorithm 56

13. 60
w

Backtracking Algorithm – Knapsack Problem

14. Branch and Bound Algorithm- Travelling Salesman Problem 63

15. Randomized Algorithm 66

3
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 1 (a) SINGLY LINKED LIST

AIM:
To write a Program to implement a single linked list

ALGORITHM:
Step 1: Start
Step 2: Read the value of ch
Step 3: If ch=1 call create list functions
Step 4: If ch=2 call insert list functions

om
Step 5: If ch=3 call delete list functions
Step 6: If ch=4 call view list functions
Step 7: Repeat while (ch! =5)
Step 8: Stop
ALGORITHM FOR CREATE LIST
Step 1: Read value of item

.c
Step 2: Allocate the memory far new node
Step 3: Assign values to new node data part
Step 4: Assign new node address part as null

ul
ALGORITHM FOR INSERT LIST
Step 1: Read the value of item
Step 2: Allocate the memory far new node
pa
Step 3: Assign values of data field as null else make link fields of all new nodes to point
Step 4: starting node to new node
Step 5: Set the external pointer from the starting node to new node
ALGORITHM FOR DELETE LIST
Step 1: If the link is empty then return else check whether the list contains more than one element
jin
Step 2: Move the start pointer to the next node
Step 3: Free the first node
ALGORITHM FOR VIEW LIST
Step 1: Using the for loop i
.re

Step 2: Print the linked list


Step 3: Stop

PROGRAM:
w

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
w

struct node
{
int item;
w

struct node *link;


};
typedef struct node NODE;
NODE *head;
NODE *getnode();
void readnode(NODE *newnode);
void createlist();
void insertfirst();

4
III SEM EEE EE2209-Data Structures and Algorithms

void deletefirst();
void viewlist();
void main()
{
int ch;
clrscr();
printf("\n\n\t\t SINGLY LINKEDLIST\n");
printf("\t\t *****************\n");
do
{

om
printf("\n 1.CREATE LIST");
printf("\n 2.INSERT FIRST");
printf("\n 3.DELETE FIRST");
printf("\n 4.VIEW LIST");
printf("\n 5.EXIT");
printf("\n\nEnter Your Choice:");

.c
scanf("%d",&ch);
switch(ch)
{

ul
case 1:
createlist();
break;
case 2:
pa
insertfirst();
break;
case 3:
deletefirst();
jin

break;
case 4:
viewlist();
break;
.re

case 5:
exit(0);
}
}
w

while(ch<=5);
}
NODE *getnode()
w

{
NODE *newnode;
newnode=(NODE*)malloc(sizeof (NODE));
w

return(newnode);
}
void readnode(NODE *newnode)
{
printf("\nEnter the item:");
scanf("%d",&newnode->item);
fflush(stdin);
newnode->link=NULL;
}
5
III SEM EEE EE2209-Data Structures and Algorithms

void createlist()
{
NODE *prev,*newnode;
char ch;
head = NULL;
do
{
newnode=getnode();
readnode(newnode);
if(head==NULL)

om
{
head=newnode;
prev=head;
}
else
{

.c
prev->link =newnode;
prev=newnode;
}

ul
printf("\nDo You Want To Continue:");
scanf("%c",&ch);
}
while(ch=='y');
pa
}
void insertfirst()
{
NODE *newnode;
jin

newnode=getnode();
readnode(newnode);
if(head==NULL)
{
.re

head=newnode;
}
else
{
w

newnode->link=head;
head=newnode;
}
w

}
void deletefirst()
{
w

NODE *prev;
if(head==NULL)
return;
else
{
prev=head;
head=head->link;
free(prev);

6
III SEM EEE EE2209-Data Structures and Algorithms

}
}
void viewlist()
{
NODE *loc;
printf("\nELEMENTS\n");
loc=head;
do
{
printf("\t%d->",loc->item);

om
loc=loc->link;
}
while(loc!=NULL); printf("NULL"); }

OUTPUT:
1.CREATE LIST

.c
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST

ul
5.EXIT
Enter Your Choice:1
Enter the item:2
pa
Do You Want To Continue:y
Enter the item:3
Do You Want To Continue:n
1.CREATE LIST
2.INSERT FIRST
jin
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:4
.re

ELEMENTS
2-> 3->NULL
1.CREATE LIST
2.INSERT FIRST
w

3.DELETE FIRST
4.VIEW LIST
5.EXIT
w

Enter Your Choice:2


Enter the item:1
1.CREATE LIST
w

2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:4
ELEMENTS
1-> 2-> 3->NULL
1.CREATE LIST
2.INSERT FIRST
7
III SEM EEE EE2209-Data Structures and Algorithms

3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:3
1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:4

om
ELEMENTS
2-> 3->NULL
1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST

.c
5.EXIT
Enter Your Choice:5

ul
pa
jin
.re
w
w
w

RESULT:

Thus the singly linked list program has been executed successfully and the output has been
verified.

8
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 1 (b) DOUBLE LINKED LIST

AIM:
To write a program to implement a Double linked list.

ALGORITHM:
Step 1: Start
Step 2: Read the value of ch
Step 3: If ch=1 call create list functions
Step 4: If ch=2 call insert list functions

om
Step 5: If ch=3 call delete list functions
Step 6: If ch=4 call view list functions
Step 7: If ch=5 call the exit functions
Step 8: Repeat while (ch! =5)
Step 9: Stop
ALGORITHM FOR CREATE LIST

.c
Step 1: Read the value of item
Step 2: Allocate the memory far newly assigned nodes
Step 3: Assign the data to the data field

ul
Step 4: Assign forward and backward link as Null
ALGORITHM FOR INSERT LIST
Step 1: Read the value of item
pa
Step 2: Allocate a new node and assign the item to the data part
Step 3: If head is NULL return
Step 4: Assign link of new node to head and blink of new node to NULL link of head node
Step 5: To new node change head ptr to print the new node
jin
ALGORITHM FOR DELETE LIST
Step 1: Check the head node as null return empty
Step 2: Else change the head pointer to the head pointer link
Step 3: Change the new head ptr blink as null
ALGORITHM FOR VIEW LIST
.re

Step 1: Using the for loop


Step 2: Print the required list
Step 3: Stop
w

PROGRAM:
#include<stdio.h>
#include<conio.h>
w

#include<alloc.h>
struct node
{
w

int item;
struct node *plink,*nlink;
};
typedef struct node NODE;
NODE *head;
NODE *getnode();
void readnode(NODE *newnode);
void createlist();
9
III SEM EEE EE2209-Data Structures and Algorithms

void insertfirst();
void deletefirst();
void viewlist();
void main()
{
int ch;
clrscr();
printf("\n\n\t DOUBLY LINKEDLIST\n");
printf("\t *****************\n");
do

om
{
printf("\n 1.CREATE LIST");
printf("\n 2.INSERT FIRST");
printf("\n 3.DELETE FIRST");
printf("\n 4.VIEW LIST");
printf("\n 5.EXIT");

.c
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)

ul
{
case 1:
createlist();
break;
pa
case 2:
insertfirst();
break;
case 3:
jin

deletefirst();
break;
case 4:
viewlist();
.re

break;
case 5:
exit(0);
}
w

}while(ch<=5);
}
NODE *getnode()
w

{
NODE *newnode;
newnode=(NODE*)malloc(sizeof(NODE));
w

return(newnode);
}
void readnode(NODE *newnode)
{
printf("\nEnter the item:");
scanf("%d",&newnode->item);
fflush(stdin);
newnode->plink=NULL;
newnode->nlink=NULL;
10
III SEM EEE EE2209-Data Structures and Algorithms

}
void createlist()
{
NODE *prev,*newnode;
char ch;
head=NULL;
do
{
newnode=getnode();
readnode(newnode);

om
if(head==NULL)
{
head=newnode;
prev=head;
}
else

.c
{
prev->nlink=newnode;
newnode->plink=prev;

ul
prev=newnode;
}
printf("\nDo you want to continue:");
scanf("%c",&ch);
pa
}
while(ch=='y');
}
void insertfirst()
jin

{
NODE *newnode;
newnode=getnode();
readnode(newnode);
.re

if(head==NULL)
{
head=newnode;
}
w

else
{
newnode->nlink=head;
w

head->plink=newnode;
head=newnode;
}
w

}
void deletefirst()
{
NODE *prev;
if(head==NULL)
return;
else
{

11
III SEM EEE EE2209-Data Structures and Algorithms

prev=head;
head=head->nlink;
head->plink=NULL;
free(prev);
}
}
void viewlist()
{
NODE *loc;
printf("\nELEMENTS\n");

om
loc=head;
do
{
printf("%2d<->",loc->item);
loc=loc->nlink;
}

.c
while(loc!=NULL);
printf("NULL");
}

ul
OUTPUT
1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
pa
4.VIEW LIST
5.EXIT
Enter Your Choice:1
Enter the item:2
jin
Do You Want To Continue:y
Enter the item:3
Do You Want To Continue:n
1.CREATE LIST
.re

2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:4
w

ELEMENTS
2<-> 3<->NULL
w

1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
w

4.VIEW LIST
5.EXIT
Enter Your Choice:2
Enter the item:1
1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
12
III SEM EEE EE2209-Data Structures and Algorithms

Enter Your Choice:4


ELEMENTS
1<-> 2<-> 3<->NULL
1.CREATE LIST
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:3
1.CREATE LIST

om
2.INSERT FIRST
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:4
ELEMENTS

.c
2<-> 3<->NULL
1.CREATE LIST
2.INSERT FIRST

ul
3.DELETE FIRST
4.VIEW LIST
5.EXIT
Enter Your Choice:5
pa
jin
.re
w
w
w

RESULT:

Thus the doubly linked list program has been executed successfully and the output has been
verified.

13
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 2 POLYNOMIAL ADDITIONS

AIM:
Represent a polynomial as a linked list and write functions for polynomial addition.

ALGORITHM:
Step 1: While p and q are not null repeat step 2
Step 2:if power of the two term are equal then if the term do not cancel then insert num of terms into the
sum polynomial advance p ,advance q, else if the power first polynomial-> power of the second then
insert the term from second polynomial in to sum polynomial advance q

om
Step 3: copy remaining terms from the non empty polynomial in to the sum polynomial

PROGRAM:
#include<stdio.h>
#include<malloc.h>
#include<conio.h>

.c
struct link
{
int coeff;

ul
int pow;
struct link *next;
};
pa
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
void create(struct link *node)
{
char ch;
do
jin
{
printf("\n enter coeff:");
scanf("%d",&node->coeff);
printf("\n enter power:");
.re

scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
printf("\n continue(y/n):");
w

ch=getch();
}
while(ch=='y' || ch=='Y');
w

}
void show(struct link *node)
w

{
while(node->next!=NULL)
{
printf("%dx^%d",node->coeff,node->pow);
node=node->next;
if(node->next!=NULL)
printf("+");
}
}
14
III SEM EEE EE2209-Data Structures and Algorithms

void polyadd(struct link *poly1,struct link *poly2,struct link *poly)


{
while(poly1->next && poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}

om
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}

.c
else
{
poly->pow=poly1->pow;

ul
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
pa
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
jin
while(poly1->next || poly2->next)
{
if(poly1->next)
{
.re

poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
w

if(poly2->next)
{
poly->pow=poly2->pow;
w

poly->coeff=poly2->coeff;
poly2=poly2->next;
}
w

poly->next=(struct link *)malloc(sizeof(struct link));


poly=poly->next;
poly->next=NULL;
}
}
main()
{
char ch;
do
15
III SEM EEE EE2209-Data Structures and Algorithms

{
poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
printf("\nenter 1st number:");
create(poly1);
printf("\nenter 2nd number:");
create(poly2);
printf("\n1st Number:");
show(poly1);

om
printf("\n2nd Number:");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\nAdded polynomial:");
show(poly);
printf("\n add two more numbers:");

.c
ch=getch();
}
while(ch=='y' || ch=='Y');

ul
return(0);
}
pa OUTPUT:
enter 1st number:
enter coeff:3
enter power:4
continue(y/n):
jin

enter coeff:6
enter power:2
continue(y/n):
enter coeff:4
.re

enter power:1
continue(y/n):
enter coeff:5
enter power:0
w

continue(y/n):
enter 2nd number:
enter coeff:2
w

enter power:3
continue(y/n):
enter coeff:3
w

enter power:1
continue(y/n):
enter coeff:7
enter power:0
continue(y/n):
1st Number:3x^4+6x^2+4x^1+5x^0
2nd Number:2x^3+3x^1+7x^0
Added polynomial:3x^4+2x^3+6x^2+7x^1+12x^0
Add two more numbers:
16
III SEM EEE EE2209-Data Structures and Algorithms

om
.c
ul
pa
jin
.re
w
w
w

RESULT:

`Thus the program for implementing polynomial addition is executed.


17
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 3 CONVERSION OF INFIX TO POSTFIX EXPRESSION

AIM:
To convert the infix to post fix expression using the concept of linked list

ALGORITHM:
Step 1: Include the header files
Step 2: Allocate the memory for linked list
Step 3: Delete the structure for the node
Step 4: Read the infix expression and find the length of the expression

om
Step 5: If the current character is open parenthesis ‘(‘then push it into the stack
Step 6: When the current character is an operand then adds it to the result
Step 7: When the current character is operator check the priority of scanned operator with top of the
stack. If the priority of the scanned character is greater than top of the stack
Step 8: If the element of the current operator is less than or equal to the top of the stack then
i) Pop the top character from the stack

.c
ii) Push the scanned operator into the stack
Step 9: When the current character is closing parenthesis then pop all the characters above opening
parenthesis if any from the stack

ul
Step10: Return the result
Step 11: End pa
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
jin
#include<ctype.h>
char pop(void);
void push(char);
int priority(char);
.re

int top;
char s[80],result[80];
void main()
{
int len,i,j;
w

char a[80];
clrscr();
printf("Enter the expression");
w

scanf("%s",a);
len=strlen(a);
w

a[len]=')';
a[len+1]='\0';
push('(');
i=0;j=0;
while(a[i])
{
if(isalpha(a[i]))
result[j++]=a[i];
else
18
III SEM EEE EE2209-Data Structures and Algorithms

{
if(a[i]=='(')
push('(');
else
{
if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/')
{
if(priority(a[i])>priority(s[top]))
push(a[i]);
else

om
{
while(priority(a[i])<priority(s[top]))
result[j++]=pop();
if (priority(a[i])==priority(s[top]))
result[j++]=pop();
push(a[i]);

.c
}
}
else

ul
{
if (a[i]==')')
{
pa
while(priority(a[i])<priority(s[top]))
result[j++]=pop();
pop();
}}}}
i++;
jin
}
result[j]='\0';
printf("Postfix expression is %s",result);
getch();
.re

}
char pop()
{
return(s[top--]);
w

}
void push(char ele)
{
w

s[++top]=ele;
}
int priority(char ch)
w

{
switch(ch)
{
case '+':return(4);
case '-':return(4);
case '*':return(5);
case '/':return(5);
case '(':return(0);
case ')':return(0);
19
III SEM EEE EE2209-Data Structures and Algorithms

}
}

OUTPUT

enter the infix expression is: a+b*c-d/e


postfix expression is: abc*+de/-

om
.c
ul
pa
jin
.re
w
w
w

RESULT:

Thus the infix expression is converted into postfix using linked list.

20
III SEM EEE EE2209-Data Structures and Algorithms

EX: NO 4 BINARY TREE TRAVERSALS


AIM:
To write a program to implement a binary tree traversal

ALGORITHM:
Step 1: Start
Step 2: Read the value of ch
Step 3: If ch=1 read the values as numbers
Step 4: While (num!=0) call insert (tree, num)
Step 5: If ch=2 call the inorder to prefer inorder traversal

om
Step 6: If ch=3 call the post order to prefer post order traversal
Step 7: If ch=4 call the pre order to prefer pre order traversal
Step 8: If ch=5 exit the operations
Step 9: Repeat while ch!=5)
Step10: End
ALGORITHM FOR INSERT

.c
Step 1: Start
Step 2: If (tree –null) allocate memory space to tree
Step 3: assign num to true ->item

ul
Step 4: Set null to tree ->child and tree->rchild
Step 5: If (num < tree -> item) insert the num on the left side of node by replacing the step
Step 6: Else (num > tree -> item) insert the num on the right side of node and repeat the Step 5
pa
Step 7: Else write duplicate value
Step 8: Return (tree)
Step 9: Stop
ALGORITHM FOR IN ORDER
Step 1: Start
jin

Step 2: If (tree! = null)


Step 3: Visit the left child
Step 4: Write tree ->item
Step 5: Visit the right child
.re

Step 6: Stop
ALGORITHM FOR PRE - ORDER
Step 1: Start
Step 2: If true! =null
w

Step 3: Write tree ->item


Step 4: Visit the left child
Step 5: Visit the right child
w

Step 6: Stop
ALGORITHM FOR POST ORDER
Step 1: Start
w

Step 2: If (true! =null)


Step 3Visit the left child
Step 4: Visit the right child
Step 5: Write tree -> item
Step 6: Stop

21
III SEM EEE EE2209-Data Structures and Algorithms

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int val;
struct node *lptr,*rptr;
};
struct node*str;

om
int ch;
void main()
{
void create(void);
void display(void);
str=NULL;

.c
clrscr();
do
{

ul
printf("\n\t BINARY TREE TRAVERSAL\n");
printf("\t *********************\n");
printf("\n 1.CREATE \n");
pa
printf("\n 2.DISPLAY\n");
printf("\n Enter ur choice:");
scanf("%d",&ch);
switch(ch)
jin
{
case 1:
create();
break;
case 2:
.re

display();
break;
}
}
w

while(ch!=2);
}
void create()
w

{
struct node *temp,*prev;
int c,n;
w

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


scanf("%d",&n);
printf("\n Enter the node elements:\n");
do
{
scanf("%d",&c);
temp=str;
if(temp==NULL)

22
III SEM EEE EE2209-Data Structures and Algorithms

{
str=(struct node*)malloc(sizeof(struct node));
temp=str;
}
else
{
while(temp!=NULL)
{
prev=temp;
if(c<temp->val)

om
temp=temp->lptr;
else
temp=temp->rptr;
}
temp=(struct node*)malloc(sizeof(struct node));
if(c<prev->val)

.c
prev->lptr=temp;
else
prev->rptr=temp;

ul
}
temp->val=c;
temp->lptr=NULL;
temp->rptr=NULL;
pa
n--;
}while(n>0);
}
void in(struct node *str)
jin
{
if(str!=NULL)
{
in(str->lptr);
.re

printf("\t%d",str->val);
in(str->rptr);
}
}
w

void pre(struct node *str)


{
if(str!=NULL)
w

{
printf("\t%d",str->val);
pre(str->lptr);
w

pre(str->rptr);
}
}
void post(struct node *str)
{
if(str!=NULL)
{
post(str->lptr);
post(str->rptr);
23
III SEM EEE EE2209-Data Structures and Algorithms

printf("\t%d",str->val);
}
}
void display()
{
void in(struct node *p);
void pre(struct node *p);
void post(struct node *p);
do
{

om
printf("\n\n 1.INORDER \n");
printf("\n 2.PREORDER\n");
printf("\n 3.POSTORDER\n");
printf("\n 4.EXIT\n");
printf("\n Enter ur choice:");
scanf("%d",&ch);

.c
switch(ch)
{
case 1:

ul
in(str);
break;
case 2:
pre(str);
pa
break;
case 3:
post(str);
break;
jin

case 4:
exit(0);
}
}while(ch!=4);
.re

}
OUTPUT

1.CREATE
w

2.DISPLAY
Enter ur choice:1
Enter the number of elements:5
w

Enter the node elements:


10
5
w

3
9
23
BINARY TREE TRAVERSAL
*********************
1.CREATE
2.DISPLAY
Enter ur choice:2
1.INORDER
24
III SEM EEE EE2209-Data Structures and Algorithms

2.PREORDER
3.POSTORDER
4.EXIT
Enter ur choice:1
3 5 9 10 23
1.INORDER
2.PREORDER
3.POSTORDER
4.EXIT
Enter ur choice:2

om
10 5 3 9 23
1.INORDER
2.PREORDER
3.POSTORDER
4.EXIT
Enter ur choice:3

.c
3 9 5 23 10
1.INORDER
2.PREORDER

ul
3.POSTORDER
4.EXIT
Enter ur choice:4
pa
jin
.re
w
w
w

RESULT:

Thus the binary tree traversal program has been executed successfully and the output has been
verified.
25
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 5 CIRCULAR QUEUE TO SIMULATE A PRODUCER-CONSUMER PROBLEM

AIM:
To write a program to implement array based circular queue to simulate producer-consumer problem.

ALGORITHM:

ALGORITHM FOR INSERTION:


Step 1: If "rear" of the queue is pointing to the last position then go to step-ii or else step-iii
Step 2: make the "rear" value as 0

om
Step 3: increment the "rear" value by one
Step 4: a. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then
it’s a "queue overflow" state, so quit; else go to step-b b. insert the new value for the queue position
pointed by the "rear".

ALGORITHM FOR DELETION:

.c
Step 1: If the queue is empty then say "empty queue" and quit; else continue
Step 2: Delete the "front" element
Step 3: If the "front" is pointing to the last position of the queue then step-iv else step-v

ul
Step 4: Make the "front" point to the first position in the queue and quit
Step 5: Increment the "front" position by one4. Terminate the program.
pa
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
jin
int frnt=-1,rear=-1,buffer[5];
void consume()
{
if(frnt==-1)
.re

printf("\n Cannot consume till producer produces it:");


else
{
printf("The consumed item is:%d",buffer[frnt]);
if(frnt==rear)
w

frnt=rear=-1;
else
frnt=((frnt+1)%5);
w

}
getch();
w

}
void producer(int x)
{
if(frnt==(rear+1)%5)
{
printf("\n Cannot produce till consumer haves it");
}
else
{
26
III SEM EEE EE2209-Data Structures and Algorithms

if(frnt==-1)
frnt=rear=0;
else
rear=((rear+1)%5);
buffer[rear]=x;
printf("\n The produced element is:%d",buffer[rear]);
}
getch();
}
void disp()

om
{
int i;
printf("\n The buffer contains:");
if(rear>=frnt)
{
for(i=frnt;i<=rear;++i)

.c
printf("%d\t",buffer[i]);
}
else

ul
{

for(i=frnt;i<5;++i)
pa
printf("%d\t",buffer[i]);
for(i=0;i<=rear;++i);
printf("%d\t",buffer[i]);
}
getch();
jin
}
void main()
{
int ch,z;
.re

do
{
clrscr();
printf("\n Producer and Consumer");
printf("\n1.Produce an item");
w

printf("\n2.Consume an item");
printf("\n3.Display the items");
printf("\n4.Exit");
w

printf("\n Enter the choice:");


scanf("\t%d",&ch);
w

switch(ch)
{
case 1:
printf("\n Enter the item to be inserted in buffer");
scanf("%d",&z);
producer(z);
break;
case 2:
consume();
27
III SEM EEE EE2209-Data Structures and Algorithms

break;
case 3:
disp();
break;
case 4:
exit(0);
break;
}
} while(ch<=4);
}

om
OUTPUT

Producer and Consumer


1.Produce an item
2.Consume an item

.c
3.Display the items
4.Exit
Enter the choice:1

ul
Enter the item to be inserted in buffer 25
The produced element is:25
Enter the choice:3
pa
The buffer contains:25
Enter the choice:2
The consumed item is:25
Enter the choice:3
jin
The buffer contains:0
Enter the choice:4
.re
w
w
w

RESULT:

Thus the program for producer consumer problem using circular queue is successfully executed.

28
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 6 BINARY SEARCH TREE

AIM:
To write a program to implement a binary search tree

ALGORITHM:
Step 1: Start
Step 2: Read the value of ch
Step 3: If ch=1 insert function should be called
Step 4: If ch=2 delete functions should be called

om
Step 5: If ch=3 view functions should be called
Step 6: If ch=4 exit insert function should be called
Step 7; Return while ch! 4
Step 8: Stop
ALGORITHM FOR INSERT:
Step 1: If (tree =null), empty allocate memory space to tree

.c
Step 2: Assign num into tree -> Lchild item
Step 3: Set null to tree ->Lchild item and free -> rchild
Step 4: If (num < tree -> item) insert num on the Lchild of the node by repeating the step 4.

ul
Step 5: Else (num > tree -> item ) insert the num on rchild of the node by repeating step 5 else
Step 6: Return tree
ALGORITHM FOR DELETE:
Step 1: Start
pa
Step 2: Assign p=tree and v=null
Step 3: Search for the element to be deleted
Step 4: Check if P-> Lchild=NULL, P->rchild inplacing node
Step 5: Check if P=NULL, condition tree print key don’t exist
jin

Step 6: Else check if p->rchild=null tree->lchild is replaced node


Step 7: Check if (f1=P) assign rp->rchild to f->Lchild and p->rchild to rp->rchild
Step 8: Assign p->lchild to rp->lchild
Step 9: Check q =null and assign replacing node is root node
.re

Step 10: Else if p=q ->lchild attaches the rp node as the last if q, otherwise attach rp nodes on right of q
ALGORITHM FOR SEARCH:
Step 1: start
Step 2: Check if (true! =NULL)
w

Step 3: Execute visit left child


Step 4: Print tree -> item
Step 5: Stop
w

PROGRAM:
#include<stdio.h>
w

#include<stdlib.h>
#include<conio.h>
#include<alloc.h>
typedef struct node
{
int data;
struct node *left,*right;
}tree;

29
III SEM EEE EE2209-Data Structures and Algorithms

void displaymenu();
void readnode(tree *);
void releasenode(tree *head);
tree *getnode();
tree *createbtree();
tree *insertnode(tree *btree,tree *temp);
tree *deletenode(int digit,tree *btree);
tree *searchnode(tree *btree,int key);
void view(tree *btree,int level);
void main()

om
{
int choice,key;
tree *btree=NULL,*temp;
clrscr();
printf("\n\n\t\tIMPLEMENTATION OF BINARY SEARCH TREE\n");
printf("\t\t************************************\n");

.c
displaymenu();
while(1)
{

ul
printf("\n Enter ur choice:");
scanf("%d",&choice);
switch(choice)
{
pa
case 0:
displaymenu();
break;
case 1:
jin

btree=NULL;
printf("\n CREATE A NEW BINARY TREE\n");
btree=createbtree();
break;
.re

case 2:
printf("\n INSERT THE NODE IN THE TREE\n");
temp=getnode();
readnode(temp);
w

btree=insertnode(btree,temp);
break;
case 3:
w

if(btree==NULL)
printf("\n BINARY TREE IS EMPTY\n");
else
w

{
printf("\n DELETE THE NODE FROM THE TREE\n");
printf("\n ENTER THE NODE FOR DELETING :");
scanf("%d",&key);
btree=deletenode(key,btree);
}
break;
case 4:

30
III SEM EEE EE2209-Data Structures and Algorithms

if(btree==NULL)
printf("\n BINARY TREE IS EMPTY\n");
else
{
printf("\n SEARCH THE NODE IN THE TREE\n\n");
printf("\n ENTER THE SEARCHING ELEMENT:");
scanf("%d",&key);
temp=searchnode(btree,key);
if(temp==NULL)
printf("\n SEARCH ELEMENT %d IS NOT FOUND",key);

om
else
printf("\n SEARCH ELEMENT %d IS FOUND ",temp->data);
}
break;
case 5:
if(btree!=NULL)

.c
{
printf("\n BINARY SEARCH TREE IS\n");
view(btree,1);

ul
}
else
printf("\n BINARY TREE IS EMPTY\n");
break;
pa
default:
printf("\n END OF THE RUN OF UR PROGRAM\n");
releasenode (btree);
exit(0);
jin
}
}
}
tree *getnode()
.re

{
int size;
tree *newnode;
size=sizeof(tree);
newnode=(tree *)malloc(size);
w

return(newnode);
}
w

void readnode(tree *newnode)


{
printf("\n ENTER THE DATA:");
w

scanf("%d",&newnode->data);
newnode->left=NULL;
newnode->right=NULL;
}
void releasenode(tree *head)
{
free(head);
}
tree *createbtree()
31
III SEM EEE EE2209-Data Structures and Algorithms

{
char ch;
tree *btree=NULL,*temp;
do
{
temp=getnode()
readnode(temp);
btree=insertnode(btree,temp);
fflush(stdin);
printf("\n DO U WISH TO ADD DATA IN THE TREE(Y/N)?");

om
scanf("%c",&ch);
}
while(ch=='y');
return btree;
}
tree *insertnode(tree *btree,tree *temp)

.c
{
if(btree==NULL)
return temp;

ul
else if(temp->data<btree->data)
btree->left=insertnode(btree->left,temp);
else if(temp->data>btree->data)
pa
btree->right=insertnode(btree->right,temp);
else if (temp->data==btree->data)
{
printf("\n DATA IS ALREADY EXISTING....");
return btree;
jin

}
return btree;
}
tree *deletenode(int key,tree *btree)
.re

{
tree *p,*fop,*suc,*fosuc;
p=btree;
fop=NULL;
w

while(p!=NULL&&p->data!=key)
{
fop=p;
w

p=(key<p->data)?p->left:p->right;
}
if(p==NULL)
w

{
printf("\n ELEMENT IS NOT FOUND ..");
return btree;
}
if(p->left!=NULL&&p->right!=NULL)
{
for(fosuc=p,suc=p->right;suc->left!=NULL;suc=suc->left)
fosuc=suc;
if(suc->right==NULL)
32
III SEM EEE EE2209-Data Structures and Algorithms

{
if(fosuc->right==suc)
fosuc->right=NULL;
else if(fosuc->left==suc)
fosuc->left=NULL;
}
else if(suc->right!=NULL)
{
if(fosuc->right==suc)
fosuc->right=suc->right;

om
else if (fosuc->left==suc)
fosuc->left=suc->right;
}
suc->left=p->left;
suc->right=p->right;
if(fop==NULL)

.c
return suc;
if(fop->left==p)
fop->left=suc;

ul
if(fop->left==p)
fop->left=suc;
else if(fop->right==p)
fop->right=suc;
pa
return btree;
}
else if(p->left==NULL&&p->right==NULL)
{
jin

if(fop==NULL)
return NULL;
else if(fop->right==p)
fop->right=NULL;
.re

else if (fop->left==p)
fop->left=NULL;
}
else if((p->left!=NULL&&p->right==NULL)||(p->left==NULL&&p->right!=NULL))
w

{
if(fop==NULL)
return((p->right!=NULL)?p->right:p->left);
w

else if(fop->right==p)
fop->right=((p->right!=NULL)?p->right:p->left);
else if(fop->left==p)
w

fop->left=((p->left!=NULL)?p->right:p->left);
}
releasenode(p);
return btree;
}
tree *searchnode(tree *btree,int key)
{
if(btree==NULL)

33
III SEM EEE EE2209-Data Structures and Algorithms

return NULL;
else if (key<btree->data)
return searchnode(btree->left,key);
else if (key>btree->data)
return searchnode(btree->right,key);
else if(key==btree->data)
return btree;
}
void view(tree *btree,int level)
{

om
int k;
if(btree==NULL)
return;
view(btree->right,level+1);
printf("\n");
for(k=0;k<level;k++)

.c
printf(" ");
printf("%d",btree->data);
view(btree->left,level+1);

ul
}
void displaymenu()
{
pa
printf("\n BASIC OPERATIONS IN A BINARY SEARCH TREE\n");
printf("\n 0.SHOW MENU");
printf("\n 1.CREATE BINARY TRE");
printf("\n 2.INSERT A NODE");
printf("\n 3.DELETE A NODE");
jin
printf("\n 4.SEARCH A NODE");
printf("\n 5.VIEW THE BINARY TREE");
printf("\n 6.EXIT\n");
}
.re

OUTPUT

BASIC OPERATIONS IN A BINARY SEARCH TREE


0. SHOW MENU
w

1. CREATE BINARY TRE


2. INSERT A NODE
3. DELETE A NODE
w

4. SEARCH A NODE
5. VIEW THE BINARY TREE
6. EXIT
w

Enter ur choice: 1
CREATE A NEW BINARY TREE
ENTER THE DATA: 10
DO U WISH TO ADD DATA IN THE TREE(Y/N)?y
ENTER THE DATA:7
DO U WISH TO ADD DATA IN THE TREE(Y/N)?y
ENTER THE DATA:9
DO U WISH TO ADD DATA IN THE TREE(Y/N)?y
ENTER THE DATA:5
34
III SEM EEE EE2209-Data Structures and Algorithms

DO U WISH TO ADD DATA IN THE TREE(Y/N)?y


ENTER THE DATA:2
DO U WISH TO ADD DATA IN THE TREE(Y/N)?n
Enter ur choice:5
BINARY SEARCH TREE IS
10
9
7
5
2

om
Enter ur choice:2
INSERT THE NODE IN THE TREE
ENTER THE DATA:6
Enter ur choice:5
BINARY SEARCH TREE IS
10

.c
9
7
6

ul
5
2
Enter ur choice:3
pa
DELETE THE NODE FROM THE TREE
ENTER THE NODE FOR DELETING: 7
Enter ur choice:5
BINARY SEARCH TREE IS
10
jin

9
6
5
2
.re

Enter ur choice:4
SEARCH THE NODE IN THE TREE
ENTER THE SEARCHING ELEMENT:7
SEARCH ELEMENT 7 IS NOT FOUND
w

Enter ur choice:4
SEARCH THE NODE IN THE TREE
ENTER THE SEARCHING ELEMENT:6
w

SEARCH ELEMENT 6 IS FOUND


Enter ur choice:6
END OF THE RUN OF UR PROGRAM
w

RESULT:

Thus the binary search tree program has been executed successfully and the output has been
verified
35
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 7 AVL TREE


AIM:
To implement AVL Rotations

ALGORITHM:
Step 1: Get the element to be inserted
Step 2: Pass the element to be inserted to the add procedure which in turn invokes insert procedure and
places the element in correct position by maintaining the height factor
Step 3: Continue step-1 till the user request otherwise exit from the process.

om
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<alloc.h>
typedef enum { FALSE ,TRUE } bool;

.c
struct node
{
int info;

ul
int balance;
struct node *lchild;
struct node *rchild;
};
pa
struct node *insert (int , struct node *, int *);
struct node* search(struct node *,int);
inorder(struct node *);
jin
display(struct node *,int n);
main()
{
int ht_inc;
int info ;
.re

int choice;
struct node *root = (struct node *)malloc(sizeof(struct node));
root = NULL;
while(1)
w

{
printf("1.Insert\n");
printf("2.Display\n");
w

printf("3.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
w

switch(choice)
{
case 1:
printf("Enter the value to be inserted : ");
scanf("%d", &info);
if( search(root,info) == NULL )
root = insert(info, root, &ht_inc);
else

36
III SEM EEE EE2209-Data Structures and Algorithms

printf("Duplicate value ignored\n");


break;
case 2:
if(root==NULL)
{
printf("Tree is empty\n");
continue;
}
printf("Tree is :\n");
display(root, 1);

om
printf("\n\n");
printf("Inorder Traversal is: ");
inorder(root);
printf("\n");
break;
case 3:

.c
exit(1);
default:
printf("Wrong choice\n");

ul
}
}
}
pa
struct node* search(struct node *ptr,int info)
{
if(ptr!=NULL)
if(info < ptr->info)
ptr=search(ptr->lchild,info);
jin

else if( info > ptr->info)


ptr=search(ptr->rchild,info);
return(ptr);
}/*End of search()*/
.re

struct node *insert (int info, struct node *pptr, int *ht_inc)
{
struct node *aptr;
struct node *bptr;
w

if(pptr==NULL)
{
pptr = (struct node *) malloc(sizeof(struct node));
w

pptr->info = info;
pptr->lchild = NULL;
pptr->rchild = NULL;
w

pptr->balance = 0;
*ht_inc = TRUE;
return (pptr);
}
if(info < pptr->info)
{
pptr->lchild = insert(info, pptr->lchild, ht_inc);
if(*ht_inc==TRUE)
{
37
III SEM EEE EE2209-Data Structures and Algorithms

switch(pptr->balance)
{
case -1: /* Right heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = 1;
break;
case 1: /* Left heavy */

om
aptr = pptr->lchild;
if(aptr->balance == 1)
{
printf("Left to Left Rotation\n");
pptr->lchild= aptr->rchild;
aptr->rchild = pptr;

.c
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;

ul
}
else
{
pa
printf("Left to right rotation\n");
bptr = aptr->rchild;
aptr->rchild = bptr->lchild;
bptr->lchild = aptr;
pptr->lchild = bptr->rchild;
jin

bptr->rchild = pptr;
if(bptr->balance == 1 )
pptr->balance = -1;
else
.re

pptr->balance = 0;
if(bptr->balance == -1)
aptr->balance = 1;
else
w

aptr->balance = 0;
bptr->balance=0;
pptr=bptr;
w

}
*ht_inc = FALSE;
}/*End of switch */
w

}/*End of if */
}/*End of if*/
if(info > pptr->info)
{
pptr->rchild = insert(info, pptr->rchild, ht_inc);
if(*ht_inc==TRUE)
{
switch(pptr->balance)

38
III SEM EEE EE2209-Data Structures and Algorithms

{
case 1: /* Left heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = -1;
break;
case -1: /* Right heavy */
aptr = pptr->rchild;

om
if(aptr->balance == -1)
{
printf("Right to Right Rotation\n");
pptr->rchild= aptr->lchild;
aptr->lchild = pptr;
pptr->balance = 0;

.c
aptr->balance=0;
pptr = aptr;
}

ul
else
{
printf("Right to Left Rotation\n");
bptr = aptr->lchild;
pa
aptr->lchild = bptr->rchild;
bptr->rchild = aptr;
pptr->rchild = bptr->lchild;
bptr->lchild = pptr;
jin

if(bptr->balance == -1)
pptr->balance = 1;
else
pptr->balance = 0;
.re

if(bptr->balance == 1)
aptr->balance = -1;
else
aptr->balance = 0;
w

bptr->balance=0;
pptr = bptr;
}/*End of else*/
w

*ht_inc = FALSE;
}/*End of switch */
}/*End of if*/
w

}/*End of if*/
return(pptr);
}/*End of insert()*/
display(struct node *ptr,int level)
{
int i;
if ( ptr!=NULL )
{
display(ptr->rchild, level+1);
39
III SEM EEE EE2209-Data Structures and Algorithms

printf("\n");
for (i = 0; i < level; i++)
printf(" ");
printf("%d", ptr->info);
display(ptr->lchild, level+1);
}
return(0);
}
inorder(struct node *ptr)
{

om
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild);
}

.c
return(0);
}
OUTPUT

ul
1.Insert
2.Display
3.Quit
pa
Enter your choice : 1
Enter the value to be inserted : 10
Right to Right Rotation
1.Insert
jin

2.Display
3.Quit
Enter your choice : 1
Enter the value to be inserted : 12
.re

Right to Right Rotation


1.Insert
2.Display
3.Quit
w

Enter your choice : 1


Enter the value to be inserted : 14
Right to Right Rotation
w

1.Insert
2.Display
3.Quit
w

Enter your choice : 1


Enter the value to be inserted : 16
1.Insert
2.Display
3.Quit
Enter your choice : 1
Enter the value to be inserted : 18
Right to Right Rotation

40
III SEM EEE EE2209-Data Structures and Algorithms

1.Insert
2.Display
3.Quit
Enter your choice : 2
Tree is :
18
16
14
12
10

om
8
6
4
2
Inorder Traversal is: 2 4 6 8 10 12 14 16 18
1.Insert

.c
2.Display
3.Quit
Enter your choice : 3

ul
pa
jin
.re
w
w
w

RESULT:

Thus the program for implementing AVL rotations is executed.

41
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 8 QUEUE USING BINARY HEAPING

AIM:
To implement binary heap

ALGORITHM:
Step 1: Get the choice which ADT to perform
i) If insert get the element to be inserted and pass it to insert function
ii) If delete call delete function
iii) If search get the element to be searched and pass it so search function

om
iv) If display call the display function
Step 2: Continue step 1 till the user request
Step 3: Exit from the process if the user don’t want to continue step 3

PRIORITY QUEUE:
PROGRAM:

.c
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

ul
#include<alloc.h>
insert();
del();
display();
pa
struct node
{
int priority;
jin
int info;
struct node *link;
}*front = NULL;
main()
.re

{
int choice;
while(1)
{
printf("1.Insert\n");
w

printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
w

printf("Enter your choice : ");


scanf("%d", &choice);
switch(choice)
w

{
case 1:
insert();
break;
case 2:
del();
break;
case 3:

42
III SEM EEE EE2209-Data Structures and Algorithms

display();
break;
default :
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
insert()
{
struct node *tmp,*q;

om
int added_item,item_priority;
tmp = (struct node *)malloc(sizeof(struct node));
printf("Input the item value to be added in the queue : ");
scanf("%d",&added_item);
printf("Enter its priority : ");
scanf("%d",&item_priority);

.c
tmp->info = added_item;
tmp->priority = item_priority;
/*Queue is empty or item to be added has priority more than first

ul
item*/
if( front == NULL || item_priority < front->priority )
{
tmp->link = front;
pa
front = tmp;
}
else
{
jin

q = front;
while( q->link != NULL && q->link->priority <= item_priority )
q=q->link;
tmp->link = q->link;
.re

q->link = tmp;
}
return(0);
}
w

del()
{
struct node *tmp;
w

if(front == NULL)
printf("Queue Underflow\n");
else
w

{
tmp = front;
printf("Deleted item is %d\n",tmp->info);
front = front->link;
free(tmp);
}
return(0);
}
display()
43
III SEM EEE EE2209-Data Structures and Algorithms

{
struct node *ptr;
ptr = front;
if(front == NULL)
printf("Queue is empty\n");
else
{ printf("Queue is :\n");
printf("Priority Item\n");
while(ptr != NULL)
{

om
printf("%5d %5d\n",ptr->priority,ptr->info);
ptr = ptr->link;
}
}
return(0);
}

.c
OUTPUT

Enter your choice : 1

ul
Input the item value to be added in the queue : 4
Enter its priority : 3
1.Insert
2.Delete
pa
3.Display
4.Quit
Enter your choice : 1
Input the item value to be added in the queue : 5
jin

Enter its priority : 2


1.Insert
2.Delete
3.Display
.re

4.Quit
Enter your choice : 1
Input the item value to be added in the queue : 6
Enter its priority : 4
w

1.Insert
2.Delete
3.Display
w

4.Quit
Enter your choice : 3
Queue is :
w

Priority Item
12
25
34
46
1.Insert
2.Delete
3.Display

44
III SEM EEE EE2209-Data Structures and Algorithms

4.Quit
Enter your choice : 2
Deleted item is 2
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 3
Queue is :
Priority Item

om
25
34
46
1.Insert
2.Delete
3.Display

.c
4.Quit
Enter your choice : 4

ul
pa
jin
.re
w
w
w

RESULT:

Thus the program for implementing heap (priority queue) ADT is executed successfully.

45
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 9 HASHING TECHNIQUES

AIM:
To implement hashing using Open Addressing

ALGORITHM:
Step 1: Get the Hash Size
Step 2: Get the element to placed inside the Hash Table perform open hashing place the element in the
particular position chain
Step 3: If the element is already in particular index, find next Empty Space

om
Step 4: If index is HashSize-1 then Index becomes 0.
Step 5: Continue step-2 till the user request otherwise exit from the process.

PROGRAM:
#include <stdio.h>
#include <conio.h>

.c
#define HSIZE 7
void main()
{

ul
int key[10],H[HSIZE]={0,0,0,0,0,0,0},hash[10],hash1,i,j,n;
clrscr();
printf("Enter no of elements:\n");
scanf("%d",&n);
pa
printf("Enter Key values:\n");
for(j=0;j<n;j++)
{
jin
scanf("%d",&key[j]);
}
printf("output:\n");
printf("Index\t\tHashtablevalue:\n");
printf("------------------------:\n");
.re

for(j=0;j<n;j++)
{
hash[j]=key[j]%HSIZE;
hash1=hash[j];
w

printf("Index=%d\n",hash1);
if(H[hash1]==0)
{
w

H[hash1]=key[j];
}
else
w

{
if(hash1==HSIZE-1)
hash1=0;
for(i=hash1;i<HSIZE;i++)
{
if(H[i]==0)
{
H[i]=key[j];

46
III SEM EEE EE2209-Data Structures and Algorithms

break;
}
}
}
}
for(i=0;i<HSIZE;i++)
{
printf("%d\t\t%d\n",i,H[i]);
}
getch();

om
}
OUTPUT

Enter no of elements:
5
Enter Key values:

.c
18
72
65

ul
34
13

Index Hashtablevalue:
pa
------------------------:
Index=4
Index=2
Index=2
jin

Index=6
Index=6
0 13
10
.re

2 72
3 65
4 18
50
w

6 34
w
w

RESULT:

Thus the program for implementing hashing is executed successfully.

47
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 10 TOPOLOGICAL SORTING

AIM:
To write a C program to implement topological sort.

ALGORITHM:
Step 1: Start the program
Step 2: Find a vertex with no incoming edges.
Step 3: Delete it along with all the edges outgoing from it.

om
Step 4: If there are more than one such vertices then break the tie randomly.
Step 5: Note the vertices that are deleted.
Step 6: All these recorded vertices give topologically sorted list.
Step 7: Stop the program.

.c
PROGRAM:
#include<stdio.h>
#define max 20

ul
int n,adj[max][max];
int front=-1,rear=-1,queue[max];
void main()
{
pa
int i,j=0,k;
int topsort[max],indeg[max];
clrscr();
create_graph();
jin
printf("\nThe Adjacency Matrix is ::\n");
display();
for(i=1;i<=n;i++)
{
.re

indeg[i]=indegree(i);
if(indeg[i]==0)
insert_queue(i);
}
while(front<=rear)
w

{
k=delete_queue();
topsort[j++]=k;
w

for(i=1;i<=n;i++)
{
if(adj[k][i]==1)
w

{
adj[k][i]=0;
indeg[i]=indeg[i]-1;
if(indeg[i]==0);
insert_queue(i);
}
}
}
48
III SEM EEE EE2209-Data Structures and Algorithms

printf("Nodes after topological sorting are ::\n");


for(i=0;i<=n;i++)
{
printf("%d",topsort[i]);
printf("\n");
}
}
create_graph()
{
int i,max_edges,origin,destin;

om
printf("Enter the number of Vertices::");
scanf("%d",&n);
max_edges=n*(n-1);
for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d(0,0 to quit): ",i);

.c
scanf("%d%d",&origin,&destin);
if((origin==0)&&(destin==0))
break;

ul
if(origin>n || destin>n || origin<=0 || destin<=0)
{
printf("Invalid Edge!!!\n");
i--;
pa
}
else
adj[origin][destin]=1;
}
jin
}
display()
{
int i,j;
.re

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d",adj[i][j]);
printf("\n");
w

}
}
insert_queue(int node)
w

{
if(rear==max-1)
w

printf("Queue Overflow!!!\n");
else
{
if(front==-1)
front=0;
rear=rear+1;
queue[rear]=node;
}
}
49
III SEM EEE EE2209-Data Structures and Algorithms

delete_queue()
{
int del_item;
if(front==-1 || front>rear)
{
printf("Queue Overflow!!!\n");
return;
}
else
{

om
del_item=queue[front];
front=front+1;
return del_item;
}
}
int indegree(int node)

.c
{
int i,in_deg=0;
for(i=1;i<=n;i++)

ul
if(adj[i][node]==1)
in_deg++;
return in_deg;
}
pa
OUTPUT
Enter the number of Vertices::7
Enter edge 1(0,0 to quit): 1 2
Enter edge 2(0,0 to quit): 1 3
jin
Enter edge 3(0,0 to quit): 1 4
Enter edge 4(0,0 to quit): 4 3
Enter edge 5(0,0 to quit): 2 4
Enter edge 6(0,0 to quit): 2 5
.re

Enter edge 7(0,0 to quit): 3 6


Enter edge 8(0,0 to quit): 4 6
Enter edge 9(0,0 to quit): 4 7
Enter edge 10(0,0 to quit): 5 4
Enter edge 11(0,0 to quit): 5 7
w

Enter edge 12(0,0 to quit): 7 6


Enter edge 13(0,0 to quit): 0 0
The Adjacency Matrix is:
w

0111000
0001100
w

0000010
0010011
0001001
0000000
0000010
Nodes after topological sorting are:
1
2
5
50
III SEM EEE EE2209-Data Structures and Algorithms

4
3
7
6

om
.c
ul
pa
jin
.re
w
w
w

RESULT:

Thus the program for topological sort is successfully executed.


51
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 11 DIJKSTRA’S ALGORITHM

AIM:
To write a C program to implement dijikstra’s algorithm to find shortest path.

ALGORITHM:
Step 1: Include all the header files
Step 2: Call allSelected( )
Step 3: Call Shortpath( )

om
Step 4: Access the functions from main
Step 5: End
ALGORITHM for ALLSELECTED ( ):
Step 1: Initialise i=0
Step 2: Check whether i<max

.c
Step 3: Check whether Selected[i]=0 Return 0
Step 4: Else Return 1
Step 5: Return

ul
ALGORITHM for SHORTPATH ( ):
Step 1: Initialise i=0, Check i<max Distance[i]=INFINITE
Step 2: Assign selected [current].distance [0]=0, Current=0
pa
Step 3: While (!allSelected(Selected)) Perform(Selected[i]= =0) Current=k Selected[current]=1 Print k

PROGRAM:
#include<stdio.h>
jin

#include<conio.h>
#define infinity 999
#define max 10
.re

int G[max][max],Q[max];
int n,path[max],p[max];
int dest,scr,y,z;
void display(int,int);
w

void main()
{
void buildgraph();
w

void dijkstra(int,int);
void insert(int,int);
w

void insertq(int);
int front,rear;
clrscr();
printf(“\nProgram for the shortest path algorithm using priority queue”);
printf(“\nEnter the number of the vertices:”);
scanf(“%d”,&n);
buildgraph();
printf(“\nEnter the source:”);
52
III SEM EEE EE2209-Data Structures and Algorithms

scanf(“%d”,&scr);
printf(“\nEnter the destination:”);
scanf(“%d”,&dest);
dijkstra(scr,dest);
for(y=1;y<=max;y++)
p[y]=infinity;
printf(“\nThe shortest path is:\n\t”);
display(dest,scr);
printf(“%d”,dest);

om
getch();
}
void display(int dest,int scr)
{
int z=1;

.c
while(dest>scr)
{
int a;

ul
a=path[dest];
if(a!=scr)
{
pa
p[z]=a;
}
else
jin
{
p[z]=a;
}
++z;
.re

dest=a;
}
for(y=max;y>0;y--)
{
w

if(p[y]!=infinity)
{
printf(“%d”,p[y]);
w

}
}
w

}
void buildgraph()
{
int i,j,v1,v2;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)

53
III SEM EEE EE2209-Data Structures and Algorithms

{
printf(“\nEnter the edge of v%d to v%d:”,i,j);
scanf(“%d”,&G[i][j]);
}
printf(“\n”);
}
}
void insertq(int index)
{

om
Q[index]=1;
}
void insert(int index,int vertex)
{
path[index]=vertex;

.c
}
void dijkstra(int scr,int dest)
{

ul
int small,dist[10],current,start,new1;
int temp,i,a[10];
void insertq(int);
pa
for(i=0;i<=n;i++)
{
a[i]=0;
jin
dist[i]=infinity;
}
Q[scr]=1;
dist[scr]=0;
.re

current=scr;
while(current!=dest)
{
small=infinity;
w

start=dist[current];
for(i=1;i<=n;i++)
{
w

if(Q[i]==0)
{
w

new1=start+G[current][i];
if(new1<dist[i])
{
dist[i]=new1;
insert(i,current);
}
if(dist[i]<small)

54
III SEM EEE EE2209-Data Structures and Algorithms

{
small=dist[i];
temp=i;
}
}
}
current=temp;
insertq(current);
}

om
printf(“\nThe minimum cost is:%d”,small);
}

OUTPUT
Program for the shortest path algorithm using priority queue

.c
Enter the number of the vertices: 3

Enter the edge of v1 to v1:0

ul
Enter the edge of v1 to v2:4
Enter the edge of v1 to v3:5
Enter the edge of v2 to v1:2
pa
Enter the edge of v2 to v2:0
Enter the edge of v2 to v3:3
Enter the edge of v3 to v1:4
Enter the edge of v3 to v2:2
jin

Enter the edge of v3 to v3:0


Enter the source: 1
Enter the destination: 3
.re

The minimum cost is: 5


The shortest path is: 1 3
w
w
w

RESULT:

Thus the program for dijikstra’s algorithm to find shortest path is successfully executed.
55
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 12 PRIMS ALGORITHM

AIM:
To implement prim’s algorithm

ALGORITHM:
Step 1: Get the no of vertex in the graph
Step 2: Get the edge details from the user i.e from which source to which destination edge is present
Step 3: Get which algorithm to perform
i) If prims call prims algorithm display the result exit from the process

om
Step 4: continue to step-1 till the user request
Step 5: Exit from the process

PROGRAM:
#include<conio.h>
#include<stdio.h>

.c
#define MAX 10
#define TEMP 0
#define PERM 1

ul
#define FALSE 0
#define TRUE 1
#define infinity 9999
struct node
pa
{
int predecessor;
int dist; /*Distance from predecessor */
jin
int status;
};
struct edge
{
int u;
.re

int v;
};
int adj[MAX][MAX];
int n;
w

create_graph();
display();
maketree(struct edge tree[MAX] , int *);
w

all_perm(struct node state[MAX]);


main()
{
w

int i;
//int path[MAX];
int wt_tree,count;
struct edge tree[MAX];
create_graph();
printf("Adjacency matrix is :\n");
display();
count = maketree(tree,&wt_tree);

56
III SEM EEE EE2209-Data Structures and Algorithms

printf("Weight of spanning tree is : %d\n", wt_tree);


printf("Edges to be included in spanning tree are : \n");
for(i=1;i<=count;i++)
{
printf("%d->",tree[i].u);
printf("%d\n",tree[i].v);
return(0);
}
create_graph()
{

om
int i,max_edges,origin,destin,wt;
printf("Enter number of vertices : ");
scanf("%d",&n);
max_edges=n*(n-1)/2;
for(i=1;i<=max_edges;i++)
{

.c
printf("Enter edge %d(0 0 to quit) : ",i);
scanf("%d %d",&origin,&destin);
if((origin==0) && (destin==0))

ul
break;
printf("Enter weight for this edge : ");
scanf("%d",&wt);
pa
if( origin > n || destin > n || origin<=0 || destin<=0)
{
printf("Invalid edge!\n");
i--;
}
jin

else
{
adj[origin][destin]=wt;
adj[destin][origin]=wt;
.re

}
}/*End of for*/
if(i<n-1)
{
w

printf("Spanning tree is not possible\n");


}
return(0);
w

}
display()
{
w

int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",adj[i][j]);
printf("\n");
}
return(0);

57
III SEM EEE EE2209-Data Structures and Algorithms

}
int maketree(struct edge tree[MAX],int *weight)
{
struct node state[MAX];
int i,min,count,current;
//int m;
int u1,v1;
*weight=0;
/*Make all nodes temporary*/
for(i=1;i<=n;i++)

om
{
state[i].predecessor=0;
state[i].dist = infinity;
state[i].status = TEMP;
}
/*Make first node permanent*/

.c
state[1].predecessor=0;
state[1].dist = 0;
state[1].status = PERM;

ul
/*Start from first node*/
current=1;
count=0; /*count represents number of nodes in tree */
pa
while( all_perm(state) != TRUE ) /*Loop till all the nodes become
PERM*/
{
for(i=1;i<=n;i++)
{
jin
if ( adj[current][i] > 0 && state[i].status == TEMP )
{
if( adj[current][i] < state[i].dist )
{
.re

state[i].predecessor = current;
state[i].dist = adj[current][i];
}
}
w

}/*End of for*/
/*Search for temporary node with minimum distance
and make it current node*/
w

min=infinity;
for(i=1;i<=n;i++)
{
w

if(state[i].status == TEMP && state[i].dist < min)


{
min = state[i].dist;
current=i;
}
}/*End of for*/
state[current].status=PERM;
/*Insert this edge(u1,v1) into the tree */
u1=state[current].predecessor;
58
III SEM EEE EE2209-Data Structures and Algorithms

v1=current;
count++;
tree[count].u=u1;
tree[count].v=v1;
/*Add wt on this edge to weight of tree */
*weight=*weight+adj[u1][v1];
}/*End of while*/
return (count);
}/*End of maketree()*/
/*This function returns TRUE if all nodes are permanent*/

om
int all_perm(struct node state[MAX] )
{
int i;
for(i=1;i<=n;i++)
if( state[i].status == TEMP )
return FALSE;

.c
return TRUE;
}/*End of all_perm()*/

ul
OUTPUT

Enter number of vertices: 3


pa
Enter edge 1(0,0 to quit): 1
2
Enter weight for this edge:1
Enter edge 2(0,0 to quit): 2
jin
3
Enter weight for this edge: 4
Enter edge 3(0,0 to quit): 3
1
Enter weight for this edge: 2
.re

Adjacency matrix:
012
104
240
w

Weight of the spanning tree: 4


Edges to be included in spanning tree are:
w

13
12
w

RESULT:

Thus the program for implementing prim’s algorithm is executed successfully

59
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 13 BACKTRACKING ALGORITHM – KNAPSACK PROBLEM

AIM:
To write a C program to solve the knapsack problem using backtracking algorithm

ALGORITHM:
Step 1: Declare the variables, array size and functions
Step 2: Get the value of number of objects and size of knapsack
Step 3: Enter weight and profit of objects
Step 4: Assign the initial values

om
Step 5: Call the necessary function and display the profit
Step 6: End of program

PROGRAM:

.c
#include<stdio.h>
#include<conio.h>
int c,cl,n,i,j,k;

ul
int q[10],x[10][10],w[10],p[10],max;
void get();
void knapsack();
void display();
pa
void get()
{
printf("Enter the number of objects:");
jin
scanf("%d",&n);
printf("Enter the size of knapsack: ");
scanf("%d",&c);
.re

printf("\nEnter the weight & profit of the objects\n");


for(i=1;i<=n;i++)
{
printf("Enter the weight %d:",i);
scanf("%d",&w[i]);
w

printf("\nEnter the profit of weight %d:",i);


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

}
}
void knapsack()
w

{
for(j=1;j<=n;j++)
{
for(i=1;i<=n;i++)
{
x[j][i]=0;
q[j]=0;
60
III SEM EEE EE2209-Data Structures and Algorithms

}
cl=c;
for(i=j;i<=n&&w[i]<=cl;i++)
{
x[j][i]=1;
cl=cl-w[i];
q[j]=q[j]+x[j][i]*p[i];
}
}

om
max=q[1];
for(i=1;i<=n;i++)
{
if(q[i]>max)
{

.c
max=q[i];
k=i;
}

ul
}}
void display()
{
pa
printf("The optimal solution \t Profit \n");
for(i=1;i<=n;i++)
{
jin
printf("\n");
for(j=1;j<=n;j++)
{
printf("%d\t",x[i][j]);
.re

}
printf("%d\t",q[i]);
}
printf("\nThe maximum Profit is: %d",max);
w

}
void main()
{
w

clrscr();
get();
w

knapsack();
display();
getch();
}

61
III SEM EEE EE2209-Data Structures and Algorithms

OUTPUT
Enter the number of objects: 3
Enter the size of knapsack: 100

Enter the weight & profit of the objects


Enter the weight 1:60

Enter the profit of weight 1:30


Enter the weight 2:30

om
Enter the profit of weight 2:20
Enter the weight 3:10
Enter the profit of weight 3:10
The optimal solution Profit

.c
1 1 1 60
0 1 1 30

ul
0 0 1 10
The maximum Profit is: 60
pa
jin
.re
w
w
w

RESULT:

Thus the program for knapsack problem using backtracking algorithm is successfully executed.

62
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 14 BRANCH AND BOUND ALGORITHM FOR TRAVELLING SALESPERSON


PROBLEM
AIM:
To write a C program to implement traveling sales man problem.

ALGORITHM:

Step 1: Start the program.


Step 2: First, find out all (n -1)! Possible solutions, where n is the number of cities.
Step 3: Determine the minimum cost by finding out the cost of everyone of these (n -1)! solutions

om
Step 4: Finally, keep the one with the minimum cost.
Step 5: Stop the program

PROGRAM:
#include<stdio.h>

.c
#include<conio.h>
#include<alloc.h>
int n;

ul
int a[10][10],list[20],bpath[20];
int i,j,bcost,tbcost;
void get();
pa
void initialize();
void calc(int list[]);
void swap(int x,int y);
jin
void perm(int,int);
void display();
void get()
{
.re

printf("Enter the number of cities:");


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

{
if(i!=j)
{
w

if(a[i][j]==-1)
{
w

printf("Enter the cost travelling from %d to %d is",i+1,j+1);


scanf("%d",&a[i][j]);
a[j][i]=a[i][j];
}
}
else a[i][j]=0;
}

63
III SEM EEE EE2209-Data Structures and Algorithms

for(i=0;i<n;i++)
list[i]=i;
}
void initialize()
{
for(i=0;i<10;i++)
for(j=0;j<10;j++)
a[i][j]=-1;
bcost=0;

om
}
void calc(int list[])
{
int t;
tbcost=0;

.c
for(j=1;j<n;j++)
{
t=a[list[j-1]][list[j]];

ul
if(t!=0)
tbcost=tbcost+a[list[j-1]][list[j]];
else
pa
tbcost=bcost+1;
}
}
jin
void swap(int x, int y)
{
int temp;
temp=x;
.re

x=y;
y=temp;
}
void perm(int k,int m)
w

{
int temp,i,j;
if(k==m)
w

{
calc(list);
w

if(bcost==0)
bcost=tbcost+1;
if((tbcost<bcost)&&(a[0][list[n-1]])!=0)
{
bcost=tbcost;
for(j=0;j<n;j++)
bpath[j]=list[j];

64
III SEM EEE EE2209-Data Structures and Algorithms

}
}
else
{
for(i=k;i<=m;i++)
{
swap(list[k],list[i]);
perm(k+1,m);
swap(list[k],list[i]);

om
}
}
}
void display()
{

.c
printf("The best path is: \n");
for(i=0;i<n;i++)
printf("%d --> ",bpath[i]+1);

ul
printf("\nThe cost is %d ",bcost+a[0][bpath[n-1]]);
}
void main()
pa
{
clrscr();
initialize();
jin
get();
perm(1,n-1);
display();
getch();
.re

OUTPUT
Enter the number of cities: 3
w

Enter the cost travelling from 1 to 2 is10


Enter the cost travelling from 1 to 3 is15
Enter the cost travelling from 2 to 3 is20
w

The best path is:


1 --> 2 --> 3 -->
w

The cost is 45

RESULT:

Thus the program for travelling salesperson problem using branch and bound algorithm is
successfully executed.

65
III SEM EEE EE2209-Data Structures and Algorithms

EX NO: 15 RANDOMIZED ALGORITHM


AIM:
To write a C program to implement randomized algorithm

ALGORITHM:
Step 1: Start the program
Step 2: Gives the input of some random numbers
Step 3: During the execution make some random choices
Step 4: Find the smallest and largest numbers of the input by randomly

om
Step 5: Print the output
Step 6: Stop the program

PROGRAM:
#include <stdio.h>

.c
#include <stdlib.h> /* required for randomize () and random () */
#include <conio.h> /* required for clrscr() */
int gen_rand(void); /* note these are declarations of functions */

ul
int find_max(int x, int y, int z);
int find_min(int x, int y, int z);
void main(void)
pa
{
int num1, num2, num3, max, min;
clrscr(); /* clear the screen */
jin
num1=gen_rand();
num2=gen_rand();
num3=gen_rand();
max=find_max(num1, num2, num3);
.re

min=find_min(num1, num2, num3);


printf("Random numbers are %d, %d, and %d\n", num1, num2, num3);
printf("Largest is %d. Smallest is %d.\n", max, min);
}
w

int gen_rand(void)
/* returns random number in range of 0 to 99 */
{
w

int n;
n=random(100); /* n is random number in range of 0 - 99 */
w

return(n);
}
int find_max( int x, int y, int z)
/* returns largest number */
{
int max;
if ((x>=y) && (x>=z))

66
III SEM EEE EE2209-Data Structures and Algorithms

{
max = x;
}
else if ((y>=x) && (y>=z))
{
max = y;
}
else
{

om
max = z;
}
return(max);
}
int find_min( int x, int y, int z)

.c
/* returns smallest number */
{
int min;

ul
if ((x<=y) && (x<=z))
{
min = x;
pa
}
else if ((y<=x) && (y<=z))
{
jin
min = y;
}
else
{
.re

min = y;
}
return(min);
}
w

OUTPUT

Random numbers are 1, 0, and 33


w

Largest is 33. Smallest is 0.


w

RESULT:

Thus the randomized algorithm has been implemented successfully.

67

You might also like