A Resource Manual for Pastors and Parish DSA Coordinators ...
DSA Manual
-
Upload
djvishalsolanki -
Category
Documents
-
view
245 -
download
0
Transcript of DSA Manual
-
8/3/2019 DSA Manual
1/46
List of Experiments
S.NO NAME OF THE PROGRAM PAGE NO
1.a Implement singly linked list
1.b Implement doubly linked list.
2. Represent a polynomial as a linked list and write functions for
polynomial addition.
3. Implement stack and use it to convert infix to postfix expression
4. Implement array-based circular queue and use it to simulate a
producer-consumer problem.
5. Implement an expression tree. Produce its pre-order, in-order,
and post-order traversals.6. Implement binary search tree.
7. Implement priority queue using heaps
8. Implement hashing techniques
9. Implement Dijkstra's algorithm using priority queues
10. Implement a backtracking algorithm for Knapsack problem
Ex No:1a Implementation of singly linked lists AimTo write a C program to implement List ADT using Linked List.
Algorithm
-
8/3/2019 DSA Manual
2/46
Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the
next element in the structure.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform thelist functions.
Step 3:- Declare necessary pointer variables as struct node data type.
Step 4:- Get a choice from the user. If the choice is create, Get first data from the user by callingthe function create( ), and display contents of the list.
Step 5:- If the choice is insert, Get data and its position by calling the function insert( ), and
assign the LINK field of the given data node according to the position. Display the contents ofthe list.
Step 6:- If the choice is delete, get the position of the data which is going to be removed from the
list and assign LINK field of the previous node to the address of the next node.
Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.Step 8:- Terminate the execution.
Program
#include
#include#include
void create();void insert();
void del();
void display();
struct node{
int data;
struct node *link;};
struct node *first=NULL,*last=NULL,*next,*prev,*cur;
void create(){
cur=(struct node *)malloc(sizeof(struct node));
printf("enter the data:");scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;}
void insert()
{int pos,c=1;
cur=(struct node*)malloc(sizeof(struct node));
printf("enter the data:");scanf("%d",&cur->data);
printf("Enter the position:");
scanf("%d",&pos);
if(pos==1&&first!=NULL)
-
8/3/2019 DSA Manual
3/46
{
cur->link=first;
first=cur;}
else
{ next=first;
while( clink;
c++;
}if(prev==NULL)
{
printf("invalid position");
}else
{cur->link=prev->link;
prev->link=cur;
}
}}
void del()
{int pos,c=1;
printf("Enter the position to be deleted");
scanf("%d",&pos);if(first==NULL)
{
printf("list is empty");}
else
if(pos==1 && first->link==NULL)
{printf("Deleted element is %d",first->data);
free(first);
first=NULL;}
else
if(pos==1 && first->link!=NULL){
cur=first;
first=first->link;
cur->link=NULL;
-
8/3/2019 DSA Manual
4/46
printf("Deleted element is %d",cur->data);
free(cur);
}else
{
next=first;while(clink;
c++;
}
cur->link=next->link;next->link=NULL;
if(next==NULL)
{
printf("invalid position");}
else{
printf("Deleted element is %d",next->data);
free(next);
}}
}
void display(){
cur=first;
printf("\n The elements in the list are:");while(cur!=NULL)
{
printf("%d\t",cur->data);cur=cur->link;
}
}
void main(){
int ch;
clrscr();printf("singly linked list:");
do
{printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Exit");
printf("\n\nEnter your option");
scanf("%d",&ch);
switch(ch)
-
8/3/2019 DSA Manual
5/46
{
case 1:
create();display();
break;
case 2: insert();
display();
break;case 3:
del();
display();
break;case 4:
exit(0);
}}
while(ch
-
8/3/2019 DSA Manual
6/46
2.Insert
3.Delete
4.ExitEnter your option 3
Enter the position to be deleted2
Deleted element is 4The elements in the list are:17
1.Create
2.Insert3.Delete
4.Exit
Enter your option 4
Ex No:1b Implementation of doubly linked lists.Aim
To write a C program to implement doubly Linked List.
Algorithm
Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to thenext element in the structure.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform thelist functions.
Step 3:- Declare necessary pointer variables as struct node data type.
Step 4:- Get a choice from the user. If the choice is create, Get first data from the user by callingthe function create( ), and display contents of the list.
Step 5:- If the choice is insert, Get data and its position by calling the function insert( ), and
assign the LINK field of the given data node according to the position. Display the contents of
the list.Step 6:- If the choice is delete, get the position of the data which is going to be removed from the
list and assign LINK field of the previous node to the address of the next node.Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.Step 8:- Terminate the execution.
Program#include#include
#include
void create();void insert();
void del();
void display();
struct node{
int data;
struct node *flink,*blink;};
struct node *first=NULL,*last=NULL,*next,*prev,*cur;
void create(){
-
8/3/2019 DSA Manual
7/46
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the data:");
scanf("%d",&cur->data);cur->flink=NULL;
cur->blink=NULL;
first=cur;last=cur;
}
void insert(){
int pos,c=1;
cur=(struct node*)malloc(sizeof(struct node));
printf("Enter the data:");scanf("%d",&cur->data);
printf("Enter the position:");
scanf("%d",&pos);
if(pos==1&&first!=NULL){
cur->flink=first;cur->blink=NULL;
first->blink=cur;
first=cur;
}else
{
next=first;while( cflink;
c++;
}if(prev==NULL)
{
printf("Invalid position");
}else
{
cur->flink=prev->flink;cur->blink=prev;
prev->flink->blink=cur;
prev->flink=cur;}
}
}
void del()
-
8/3/2019 DSA Manual
8/46
{
int pos,c=1;
printf("Enter the position to be deleted");scanf("%d",&pos);
if(first==NULL)
{ printf("DLL is empty");
}
elseif(pos==1 && first->flink==NULL)
{
printf("Deleted element is %d",first->data);
free(first);first=NULL;
last=NULL;
}
elseif(pos==1 && first->flink!=NULL)
{cur=first;
first=first->flink;
cur->flink=NULL;
first->blink=NULL;}
else
{next=first;
while(cflink;
c++;}
if(next==NULL)
{
printf("Invalid position");}
else
{cur->flink=next->flink;
next->flink->blink=cur;
next->flink=NULL;next->blink=NULL;
printf("Deleted element is %d",next->data);
free(next);
}
-
8/3/2019 DSA Manual
9/46
}
}
void display(){
cur=first;
printf("\n The elements in the list are:");while(cur!=NULL)
{
printf("%d\t",cur->data);cur=cur->flink;
}
}
void main(){
int ch;
clrscr();
printf("Doubly linked list:");do
{printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Exit");
printf("\n\nEnter your option");
scanf("%d",&ch);
switch(ch){
case 1:
create();display();
break;
case 2:insert();
display();
break;case 3:
del();
display();
break;case 4:
exit(0);
}
}
while(ch
-
8/3/2019 DSA Manual
10/46
2.Insert
3.Delete
4.ExitEnter your option 1
Enter the data:1
The elements in the list are:11.Create
2.Insert
3.Delete4.Exit
Enter your option2
Enter the data:4
Enter the position:2The elements in the list are:1 4
1.Create
2.Insert
3.Delete4.Exit
Enter your option 2Enter the data:7
Enter the position:3
The elements in the list are:1 4 7
1.Create2.Insert
3.Delete
4.ExitEnter your option3
Enter the position:3
The elements in the list are:1 41.Create
2.Insert
3.Delete4.Exit
Enter your option 4
Ex No:2 Addition of two polynomial using linked list
AimTo Represent a polynomial as a linked list and write functions for polynomial addition.
Algorithm
Addition of two polynomialsConsider addition of the following polynomials
5 x12 + 2 x9 + 4x7 + 6x6 + x3
7 x8 + 2 x7 + 8x6 + 6x4 + 2x2 + 3 x + 40The resulting polynomial is going to be
5 x12 + 2 x9 + 7 x8 + 6 x7 + 14x6 + 6x4 +x3 2x2 + 3 x + 40
Step 1: We started with the highest power in any polynomial. If there was no item having sameexponent, we simply appended the term to the new list, and continued with the process.
-
8/3/2019 DSA Manual
11/46
Step 2: Wherever we found that the exponents were matching, we simply added the coefficients
and then stored the term in the new list.
Step 3: If one list gets exhausted earlier and the other list still contains some lower order terms,then simply append the remaining terms to the new list.
Step 4: Let phead1, phead2 and phead3 represent the pointers of the three lists under
consideration.Step 5: Let each node contain two integers exp and coff .
Step 6: Let us assume that the two linked lists already contain relevant data about the two
polynomials.Also assume that we have got a function append to insert a new node at the end ofthe given list.
Program#include
#include#include
struct link
{
int coeff;int pow;
struct link *next;};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
void create(struct link *node)
{
char ch;
do{
printf("\n Enter coeff:");scanf("%d",&node->coeff);printf("\n Enter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));node=node->next;
node->next=NULL;
printf("\n Continue(y/n):");
ch=getch();}
while(ch=='y' || ch=='Y');
}void show(struct link *node)
{
while(node->next!=NULL){
printf("%dx^%d",node->coeff,node->pow);
node=node->next;if(node->next!=NULL)
-
8/3/2019 DSA Manual
12/46
printf("+");
}
}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;
}else if(poly1->powpow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;poly2=poly2->next;
}else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;poly1=poly1->next;
poly2=poly2->next;
}poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;}
while(poly1->next || poly2->next)
{if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;poly1=poly1->next;
}
if(poly2->next){
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
-
8/3/2019 DSA Manual
13/46
poly->next=NULL;
}
}main()
{
char ch;do
{
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);printf("\n2nd Number:");
show(poly2);polyadd(poly1,poly2,poly);
printf("\nAdded polynomial:");
show(poly);
printf("\n Add two more numbers:");ch=getch();
}
while(ch=='y' || ch=='Y');}
OutputEnter 1st number:Enter coeff:2
Enter power:2
Continue(y/n):yEnter coeff:2
Enter power:1
Continue(y/n):y
Enter coeff:2Enter power:0
Continue(y/n):n
Enter 2nd number:Enter coeff:1
Enter power:2
Continue(y/n):yEnter coeff:1
Enter power:1
Continue(y/n):yEnter coeff:1
-
8/3/2019 DSA Manual
14/46
Enter power:0
1st Number:2x^2+2x^1+2x^0
2nd Number:1x^2+1x^1+1x^0Added polynomial:3x^2+3x^1+3x^0
Add two more numbers: n
Ex No: 3 Implement a stack and use it to convert infix to postfix expressionAim To write a C program to implement a stack and convert the infix expression to postfix
expression .
AlgorithmStep 1:- Make an empty Stack.
Step 2:- Read an expression.Step 3:- Scan the expression from left to right and repeat steps 2 & 3 for each
element in the expression.
Step 4:- If an operand is encountered, push it on to the stack.
Step 5:- If an operator is encounters, then
a) Remove the two top elements from the stack.b) Perform the required operation.
c) Place the result back on to the stack.Step 6:- Set value equal to the top most element on stack.
Step 7:- Terminate the execution.
Program#include
#include
int stack[20],top=0;char intr[40],post[40];
void push();
char pop();void postfix(){
int i,j=0;
for(i=0;intr[i]!=NULL;i++){
switch(intr[i])
{case'+':while(stack[top]>=1)
post[j++]=pop();
push(1);
break;case'-':while(stack[top]>=2)
post[j++]=pop();
push(2);break;
case'*':while(stack[top]>=3)
post[j++]=pop();push(3);
-
8/3/2019 DSA Manual
15/46
break;
case'/':while(stack[top]>=4)
post[j++]=pop();push(4);
break;
case'^':while(stack[top]>=5)post[j++]=pop();
push(5);
break;case'(':push(0);
break;
case')':while(stack[top]!=0)
post[j++]=pop();
top--;
break;
default:
post[j++]=intr[i];
}
}
while(top>0)
post[j++]=pop();
printf("\n Post fix expression is:: %s",post);
}
void push(int de)
{
top++;stack[top]=de;
}
char pop()
{
char e;
e=stack[top];
top--;
switch(e)
{
case 1:e='+';break;
case 2:e='-';
break;
case 3:e='*';
break;
case 4:e='/';
-
8/3/2019 DSA Manual
16/46
break;
case 5:e='^';
break;
}
return(e);
}
void main()
{
clrscr();
printf("\n\t\t*********** Infix to postfix******************");
printf("\nEnter the infix expression");
scanf("%s",intr);
postfix();
getch();
}Output:
*********** Infix to postfix******************
Enter the infix expression
((a*b)+(b*c)/(c*d))
Post fix expression is:: ab*bc*cd*/+
Ex No:4 Implement an array based circular queue and use it to simulate a
producer-consumer problem.
Aim:To implement array based circular queue and use it to simulate a producer-consumer
problem.Algorithm for Insertion
Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3
Step-2: Make the "rear" value as 0
Step-3: Increment the "rear" value by oneStep-4: 1. If the "front" points where "rear" is pointing and the queue holds a not NULL
value for it, then its a "queue overflow" state, so quit; else go to step-4.
2. Insert the new value for the queue position pointed by the "rear"
Algorithm for deletionStep-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-4 else step-5Step-4: Make the "front" point to the first position in the queue and quit
Step-5: Increment the "front" position by one
Program
#include
#include
#include#include
-
8/3/2019 DSA Manual
17/46
#define size 3
char cqueue[size];
int front=-1,rear;void producer_enqueue(int element);
int consumer_dequeue();
void main(){
int ch,elem;
char c;clrscr();
do
{
printf("\n\t\t\t\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");printf("ENTER YOUR CHOICE");
scanf("%d",&ch);
switch(ch)
{ case 1:
printf("\n enter the element");scanf("%d",&elem);
producer_enqueue(elem);
break;
case 2:elem=consumer_dequeue();
if(elem!=-1)
printf("\consumer element is %d",elem);break;
case 3:
exit(0);}
printf("\nCONTINUE Y/N ?\n");
c=getch();}while(c=='y'||c=='Y');
}
void producer_enqueue(int element)
{if(front==(rear+1)%size)
{
printf("\n consumer queue is full\n");}
else
{if(front==-1)
front=rear=0;
else
rear=(rear+1)%size;
-
8/3/2019 DSA Manual
18/46
cqueue[rear]=element;
}
}int consumer_dequeue()
{
int element=-1;if(front==-1)
{
printf("\n the consumer queue is empty\n");}
else
{
element=cqueue[front];if(front==rear)
front=rear=-1;
else
front=(front+1)%size;}
return element;}
Output:
1.PRODUCER
2.CONSUMER3.EXIT
ENTER YOUR CHOICE 1
enter the element1CONTINUE Y/N ?
1.PRODUCER
2.CONSUMER3.EXIT
ENTER YOUR CHOICE 1
enter the element4CONTINUE Y/N ?
1.PRODUCER
2.CONSUMER
3.EXITENTER YOUR CHOICE 2
consumer element is 1
CONTINUE Y/N ?
Ex No:5 Implement an expression tree and produce its pre-order, in-order,
and post-order traversals.Aim:
To implement an expression tree and produce its pre-order, in-order, and post-order
traversals.
Algorithm:
-
8/3/2019 DSA Manual
19/46
a. To traverse a non-empty binary tree in preorder, perform the following operations
recursively at each node, starting with the root node:
1. Visit the root.2. Traverse the left subtree.
3. Traverse the right subtree.
b. To traverse a non-empty binary tree in inorder, perform the following operationsrecursively at each node:
1. Traverse the left subtree.
2. Visit the root.3. Traverse the right subtree
c. To traverse a non-empty binary tree in postorder, perform the following operations
recursively at each node:
1. Traverse the left subtree.2. Traverse the right subtree.
3. Visit the root
Program
#include#include
#include#include
void push(struct enode*);
struct enode* pop(void);void infix(struct enode*);
void prefix(struct enode*);
void postfix(struct enode*);
char equation[25];struct enode* stack[25];
int top = -1;struct enode{
char item;
struct enode* lchild;struct enode* rchild;
}*root;
int main(void)
{int count;
char ch;
printf("\n\nEnter equation in the form of postfix: ");gets(equation);
printf("\nYou have entered: ");
puts(equation);for(count = 0; equation[count] != '\0'; count++)
{
ch=equation[count];if(isalpha(ch))
-
8/3/2019 DSA Manual
20/46
{
root = (struct enode*)malloc(sizeof(struct enode));
root->item = ch;root->rchild = NULL;
root->lchild = NULL;
push(root);}
else if(ispunct(ch))
{root = (struct enode*)malloc(sizeof(struct enode));
root->item = ch;
root->rchild = pop();
root->lchild = pop();push(root);
} else
{
printf("\nSorry unrecognized entry");}
}
while(1)
{
printf("\nSelect the output form:\n 1) [i]nfix\n 2) p[r]efix\n 3) p[o]stfix \n 4) e[x]it\nEnteru r choice: ");
ch = getche();
printf("\n");switch(ch)
{
case 'i':printf("\nInorder representation of output is: ");
infix(stack[top]);
break;
case 'r':
printf("\nPreorder representation of output is: ");
prefix(stack[top]);break;
case 'o':printf("\nPostorder representation of output is: ");
postfix(stack[top]);
break;
case 'x':
printf("\nYou have pressed the button other than given choices");
exit(0);
-
8/3/2019 DSA Manual
21/46
default:
printf("\nENTER THE CORRECT OPTION");}
getch();
}}
void infix(struct enode* root){
if(root->lchild != NULL) infix(root->lchild);
printf("%c", root->item);
if(root->rchild !=NULL) infix(root->rchild);}
void prefix(struct enode* root)
{ printf("%c", root->item);
if(root->lchild != NULL) prefix(root->lchild);if(root->rchild !=NULL) prefix(root->rchild);
}
void postfix(struct enode* root)
{if(root->lchild != NULL) postfix(root->lchild);
if(root->rchild !=NULL) postfix(root->rchild);
printf("%c", root->item);}
struct enode* pop(void){
return(stack[top--]);
}
void push(struct enode* root)
{stack[++top] = root;
}
Output:
Enter equation in the form of postfix: ab+cde+**
You have entered: ab+cde+**Select the output form:
1) [i]nfix
2) p[r]efix
3) p[o]stfix
-
8/3/2019 DSA Manual
22/46
4) e[x]it
Enter u r choice: i
Inorder representation of output is: a+b*c*d+eSelect the output form:
1) [i]nfix
2) p[r]efix3) p[o]stfix
4) e[x]it
Enter u r choice: rPreorder representation of output is: *+ab*c+de
Select the output form:
1) [i]nfix
2) p[r]efix3) p[o]stfix
4) e[x]it
Enter u r choice: o
Postorder representation of output is: ab+cde+**Select the output form:
1) [i]nfix2) p[r]efix
3) p[o]stfix
4) e[x]it
Enter u r choice:x
ExNo:6 Implement a binary search tree.
Aim To write a C program to implement Binary Search Tree ADT.
Algorithm
1.Create a memory space for the Root node and initialize the value tozero.
2.Read the value.
3.If the value is less than the root value,it is assigne das the left child of
the root.Else if new value is greater than the root value,it is assigned asthe right child of the root. Else if there si no value in the root, the new
value is assigned as the root
4. Repeat the step(2) and (3) to insert the n number of values
Search Operation:
1. Read the key value to be searched
2. check whether the root is not null
3. if the value to be searched is less than the root, consider the left sub tree forsearching the particular element else if the value is greater than the root consider the
right sub-tree to search the particular element else if he value is equal then return that
is the value which was searched. Insertion:
1. Read the key value to be deleted
2. First perform the search operation to check whether the key values are different fromthose existing element.
-
8/3/2019 DSA Manual
23/46
3. If the search is unsuccessful, then the key is inserted at the point the search is
terminated.
Deletion:1. Read the key value to be deleted
2. First perform search operation to get the particular key element
3. If it is, check whethera. It is leaf node,
b. Or it has only one sub-tree
c. Or it has exactly 2 sub-trees.4. if the key value is the leaf-node, assign null value to that node, else if the key
contains only one sub-tree either left (or) right sub-tree, if the key is root, it is
discarded and its single sub-tree becomes the new search tree root. Else if the key is
the child node, then we change the pointer from the root of key to the child of the key
5. If the key contains both left and right sub-tree replace the key with either largest
element in the left sub-tree or smallest in the right sub-tree.
Program:
#include#include
#include#include
struct tree
{int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;int element;
void inorder(struct tree *);void preorder(struct tree *);void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);void main()
{
int ch;
do
{printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
-
8/3/2019 DSA Manual
24/46
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);switch(ch)
{
case 1:printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);inorder(t);
break;
case 2:
printf("\nEnter the data:");scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;case 3:
printf("\nEnter the data:");scanf("%d",&element);
t=del(t,element);
inorder(t);
break;case 4:
printf("\nEnter the data:");
scanf("%d",&element);temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);else
printf("\nElement is not found");
break;case 5:
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;case 6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);break;
case 7:
inorder(t);break;
case 8:
preorder(t);
break;
-
8/3/2019 DSA Manual
25/46
case 9:
postorder(t);
break;case 10:
exit(0);
}}while(chdata=element;
t->lchild=NULL;t->rchild=NULL;
return t;
}
struct tree * find(struct tree *t, int element){
if(t==NULL)return NULL;
if(elementdata)
return(find(t->lchild,element));
elseif(element>t->data)
return(find(t->rchild,element));
elsereturn t;
}
struct tree *findmin(struct tree *t){
if(t==NULL)
return NULL;else
if(t->lchild==NULL)
return t;
elsereturn(findmin(t->lchild));
}
struct tree *findmax(struct tree *t){
if(t!=NULL)
{while(t->rchild!=NULL)
t=t->rchild;
}
return t;
-
8/3/2019 DSA Manual
26/46
}
struct tree *insert(struct tree *t,int element)
{if(t==NULL)
{
t=(struct tree *)malloc(sizeof(struct tree));t->data=element;
t->lchild=NULL;
t->rchild=NULL;return t;
}
else
{if(elementdata)
{
t->lchild=insert(t->lchild,element);
}else
if(element>t->data){
t->rchild=insert(t->rchild,element);
}
elseif(element==t->data)
{
printf("element already present\n");}
return t;
}}
struct tree * del(struct tree *t, int element)
{if(t==NULL)
printf("element not found\n");
else
if(elementdata)t->lchild=del(t->lchild,element);
else
if(element>t->data)t->rchild=del(t->rchild,element);
else
if(t->lchild&&t->rchild){
temp=findmin(t->rchild);
t->data=temp->data;
t->rchild=del(t->rchild,t->data);
-
8/3/2019 DSA Manual
27/46
}
else
{temp=t;
if(t->lchild==NULL)
t=t->rchild;else
if(t->rchild==NULL)
t=t->lchild;free(temp);
}
return t;
}void inorder(struct tree *t)
{
if(t==NULL)
return;else
{inorder(t->lchild);
printf("\t%d",t->data);
inorder(t->rchild);
}}
void preorder(struct tree *t)
{if(t==NULL)
return;
else{
printf("\t%d",t->data);
preorder(t->lchild);preorder(t->rchild);
}
}
void postorder(struct tree *t){
if(t==NULL)
return;else
{
postorder(t->lchild);postorder(t->rchild);
printf("\t%d",t->data);
}
}
-
8/3/2019 DSA Manual
28/46
Output:
BINARY SEARCH TREE
****** ****** ****Main Menu
1.Create
2.Insert3.Delete
4.Find
5.FindMin6.FindMax
7.Inorder
8.Preorder
9.Postorder10.Exit
Enter ur choice :1
Enter the data:10
10 BINARY SEARCH TREE
****** ****** ****Main Menu
1.Create
2.Insert
3.Delete4.Find
5.FindMin
6.FindMax7.Inorder
8.Preorder
9.Postorder10.Exit
Enter ur choice :2
Enter the data:2010 20
BINARY SEARCH TREE
****** ****** ****
Main Menu1.Create
2.Insert
3.Delete4.Find
5.FindMin
6.FindMax7.Inorder
8.Preorder
9.Postorder
10.Exit
-
8/3/2019 DSA Manual
29/46
Enter ur choice :2
Enter the data:30
10 20 30BINARY SEARCH TREE
****** ****** ****
Main Menu1.Create
2.Insert
3.Delete4.Find
5.FindMin
6.FindMax
7.Inorder8.Preorder
9.Postorder
10.Exit
Enter ur choice :2Enter the data:25
10 20 25 30BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create2.Insert
3.Delete
4.Find5.FindMin
6.FindMax
7.Inorder8.Preorder
9.Postorder
10.ExitEnter ur choice :4
Enter the data:25
Element 25 is at 2216
BINARY SEARCH TREE****** ****** ****
Main Menu
1.Create2.Insert
3.Delete
4.Find5.FindMin
6.FindMax
7.Inorder
8.Preorder
-
8/3/2019 DSA Manual
30/46
9.Postorder
10.Exit
Enter ur choice :5Max element=10
BINARY SEARCH TREE
****** ****** ****Main Menu
1.Create
2.Insert3.Delete
4.Find
5.FindMin
6.FindMax7.Inorder
8.Preorder
9.Postorder
10.ExitEnter ur choice :6
Max element=30BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create2.Insert
3.Delete
4.Find5.FindMin
6.FindMax
7.Inorder8.Preorder
9.Postorder
10.ExitEnter ur choice :7
10 20 25 30
BINARY SEARCH TREE
****** ****** ****Main Menu
1.Create
2.Insert3.Delete
4.Find
5.FindMin6.FindMax
7.Inorder
8.Preorder
9.Postorder
-
8/3/2019 DSA Manual
31/46
10.Exit
Enter ur choice :8
10 20 30 25BINARY SEARCH TREE
****** ****** ****
Main Menu1.Create
2.Insert
3.Delete4.Find
5.FindMin
6.FindMax
7.Inorder8.Preorder
9.Postorder
10.Exit
Enter ur choice :925 30 20 10
BINARY SEARCH TREE****** ****** ****
Main Menu
1.Create
2.Insert3.Delete
4.Find
5.FindMin6.FindMax
7.Inorder
8.Preorder9.Postorder
10.Exit
Enter ur choice :3Enter the data:10
20 25 30
BINARY SEARCH TREE
****** ****** ****Main Menu
1.Create
2.Insert3.Delete
4.Find
5.FindMin6.FindMax
7.Inorder
8.Preorder
9.Postorder
-
8/3/2019 DSA Manual
32/46
10.Exit
Enter ur choice :10
Ex No: 7 Implement Priority Queue using heaps
Aim:To write a C program to Implement Priority Queue using heaps
Algorithm
InsertionStep1: To insert an element X in to the heap, create a hole in the next available location,
otherwise the tree will not be complete.
Step2: If X can be placed in the hole without violating heap order, then place the element X thereitself.
Step3: Otherwise slide the element that is in the holes parent node in the hole, thus bubbling the
hole up towards the root.Step4: This process continues until X can be placed in the hole
Step5: This general strategy is known as percolate up, in which the new element is percolated up
the heap until the correct location is found.
Delete MinStep1: In binary heap the minimum element is found in the root.
Step2; When this minimum is removed, a hole is created at the root. Since the heap becomes onesmaller, makes the last element X in the heap to move somewhere in the heap.
Step3: If X can be placed in hole without violating heap order property place it. Otherwise slide
the smaller of the holes children in to the hole, thus pushing the hole down one level.
Step4: Repeat until X can be placed in the hole. This general strategy is known as percolatedown.
Program:#include#include
#include
#include#include
struct heapnode
{int capacity;
int size;
int *elements;
};int isFull(struct heapnode *h)
{
if(h->capacity==h->size)return 1;
else
return 0;}
int isEmpty(struct heapnode *h)
{
if(h->size==0)
-
8/3/2019 DSA Manual
33/46
return 1;
else
return 0;}
void display(struct heapnode *h)
{ printf("\nPriority Queue Display :");
if(isEmpty(h))
{printf("\nPriority queue is empty");
return;
}
elsefor(int i=1;isize;i++)
printf("%d\t",h->elements[i]);
}struct heapnode * initialize()
{struct heapnode *t;
int maxelements;
printf("\nEnter the Size of the Priority queue :");
scanf("%d",&maxelements);
if(maxelementselements=(int *)malloc((maxelements+1)*sizeof(int));
if(t->elements==NULL){
printf("Out of space");
getch();
exit(0);
-
8/3/2019 DSA Manual
34/46
}
t->capacity=maxelements;t->size=0;
t->elements=0;
return t;}
void insert(int x,struct heapnode *h)
{int i;
if(isFull(h))
{
printf("Priority queue is full");return;
}
for(i=++h->size;h->elements[i/2]>x;i/=2)
h->elements[i]=h->elements[i/2];h->elements[i]=x;
}int deleteMin(struct heapnode *h)
{
int i,child;
int MinElement,LastElement;
if(isEmpty(h))
{printf("Priority queue is empty");
return 0;
}
MinElement=h->elements[1];
LastElement=h->elements[h->size--];
for(i=1;i*2size;i=child)
{
child=i*2;if(child!=h->size&&h->elements[child+1]elements[child])
child++;
if(LastElement>h->elements[child])h->elements[i]=h->elements[child];
else
break;}
h->elements[i]=LastElement;
return MinElement;
}
-
8/3/2019 DSA Manual
35/46
void main()
{
int ch,ins,del;struct heapnode *h;
clrscr();
printf("\nPriority Queue using Heap");h=initialize();
while(1)
{printf("\n1. Insert\n2. DeleteMin\n3. Display\n4. Exit");
printf("\nEnter u r choice :");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\nEnter the element:");
scanf("%d",&ins);insert(ins,h);
break;case 2:
del=deleteMin(h);
printf("\nDeleted element is %d",del);
getch();break;
case 3:
display(h);getch();
break;
case 4:exit(0);
}
}}
Output:
Priority Queue using Heap
Enter the Size of the Priority queue :141. Insert
2. DeleteMin
3. Display4. Exit
Enter u r choice :1
Enter the element:101. Insert
2. DeleteMin
3. Display
4. Exit
-
8/3/2019 DSA Manual
36/46
Enter u r choice :1
Enter the element:34
1. Insert2. DeleteMin
3. Display
4. ExitEnter u r choice :1
Enter the element:24
1. Insert2. DeleteMin
3. Display
4. Exit
Enter u r choice :1Enter the element:67
1. Insert
2. DeleteMin
3. Display4. Exit
Enter u r choice :3Priority Queue Display :10 34 24 67
1. Insert
2. DeleteMin
3. Display4. Exit
Enter u r choice :2
Deleted element is 101. Insert
2. DeleteMin
3. Display4. Exit
Enter u r choice :2
Deleted element is 241. Insert
2. DeleteMin
3. Display
4. ExitEnter u r choice :3
Priority Queue Display :34 67
1. Insert2. DeleteMin
3. Display
4. ExitEnter u r choice :4
Ex No:8 Implement Hashing Technique Separate ChainingAim: To write a C program to implement separate chaining.
Algorithm
-
8/3/2019 DSA Manual
37/46
Step1:A pointer field is added to each record location. When a new key arrives the linked list is
extended .
Step2:To insert an element, traverse down the appropriate list to check whether the element isalready in place.
Step3: If the element turns to be new one it is inserted either at the front of the list or at the end
of the list.Step4: If it is a duplicate element , an extra field is kept and placed
Program:#include #include
#include
struct listnode
{int element;
struct listnode *next;
};
struct hashtbl{
int tablesize;struct listnode **thelists;
};
int hash(int key,int tablesize){
return (key%tablesize);
}
struct hashtbl * initializetable(int tablesze){
struct hashtbl *h;int i;if(tableszetablesize=tablesze;h->thelists=(struct listnode **)malloc(sizeof(struct listnode *)*h->tablesize);
if(h->thelists==NULL){
-
8/3/2019 DSA Manual
38/46
printf("ouf of space!!!");
getch();
exit(0);}
for(i=0;itablesize;i++)
{ h->thelists[i]=(struct listnode *)malloc(sizeof(struct listnode *));
if(h->thelists[i]==NULL)
{printf("out of space !!!");
getch();
exit(0);
}else
//h->thelists[i]=NULL;
h->thelists[i]->next=NULL;
}return h;
}void display(struct hashtbl *h)
{
struct listnode *p,*l;
printf("\nDisplay\n");for(int i=0;itablesize;i++)
{
l=h->thelists[i];p=l->next;
printf("%d",i);
do{
if(p!=NULL)
printf("-->\t%d",p->element);else
{
printf("--> %s","NULL");
break;}
p=p->next;
}while(1);printf("\n");
}
getch();}
struct listnode * find(int key,struct hashtbl *h)
{
struct listnode *p,*l;
-
8/3/2019 DSA Manual
39/46
l=h->thelists[hash(key,h->tablesize)];
p=l->next;
while(p!=NULL && p->element!=key)p=p->next;
return p;
}void insert(int key,struct hashtbl *h)
{
struct listnode *pos,*newcell,*l;pos=find(key,h);
if(pos==NULL)
{
newcell=(struct listnode *)malloc(sizeof(struct listnode *));if(newcell==NULL)
{
printf("out of space!!!");
getch();exit(0);
}else
{
l=h->thelists[hash(key,h->tablesize)];
newcell->next=l->next;newcell->element=key;
l->next=newcell;
}}
}
void main(){
int ch,ins,found;
struct hashtbl *h;struct listnode *p;
clrscr();
printf("\nSeparate Chaining using Hash Function");
h=initializetable(10);while(1)
{
printf("\n1. Insert\n2. Find\n3. Display\n4. Exit");printf("\nEnter u r choice :");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\nEnter the element to insert:");
scanf("%d",&ins);
-
8/3/2019 DSA Manual
40/46
insert(ins,h);
break;
case 2:printf("\nEnter the element to find:");
scanf("%d",&found);
p=find(found,h);if(p==NULL)
printf("Element is not found");
elseprintf("\nThe element %d is found",found);
getch();
break;
case 3:display(h);
getch();
break;
case 4: exit(0);
}}
}
Output :
Separate Chaining using Hash Function1. Insert
2. Find
3. Display4. Exit
Enter u r choice :1
Enter the element to insert:101. Insert
2. Find
3. Display4. Exit
Enter u r choice :1
Enter the element to insert:20
1. Insert2. Find
3. Display
4. ExitEnter u r choice :1
Enter the element to insert:34
1. Insert2. Find
3. Display
4. Exit
Enter u r choice :1
-
8/3/2019 DSA Manual
41/46
Enter the element to insert:56
1. Insert
2. Find3. Display
4. Exit
Enter u r choice :3Display
0--> 20--> 10--> NULL
1--> NULL2--> NULL
3--> NULL
4--> 34--> NULL
5--> NULL6--> 56--> NULL
7--> NULL
8--> NULL
9--> NULL1. Insert
2. Find3. Display
4. Exit
Enter u r choice :2
Enter the element to find:20The element 20 is found
1. Insert
2. Find3. Display
4. Exit
Enter u r choice :2Enter the element to find:100
Element is not found
1. Insert2. Find
3. Display
4. Exit
Enter u r choice :4
Ex No:9 Implement Dijkstra's algorithm using priority queues
Aim:
To write a C program to Implement Dijkstra's algorithm using priority queuesAlgorithm
1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for
all other nodes.2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbors and calculate their distance (from
the initial node). For example, if current node (A) has distance of 6, and an edge
-
8/3/2019 DSA Manual
42/46
connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If
this distance is less than the previously recorded distance (infinity in the beginning, zero
for the initial node), overwrite the distance.
4. When we are done considering all neighbors of the current node, mark it as visited. A
visited node will not be checked ever again; its distance recorded now is final and
minimal.5. Set the unvisited node with the smallest distance (from the initial node) as the next
"current node" and continue from step 3 .
Program:#include< stdio.h>
#include< conio.h>
#include< process.h>
#include< string.h>#include< math.h>
#define IN 99
#define N 6
int dijkstra(int cost[][N], int source, int target);void main()
{int cost[N][N],i,j,w,ch,co;
int source, target,x,y;
clrscr();printf("\tShortest Path Algorithm(DIJKSRTRA's ALGORITHM\n\n");
for(i=1;i< N;i++)
for(j=1;j< N;j++)
cost[i][j] = IN;for(x=1;x< N;x++)
{for(y=x+1;y< N;y++){
printf("Enter the weight of the path between node %d and %d: ",x,y);
scanf("%d",&w);cost [x][y] = cost[y][x] = w;
}
printf("\n");
}printf("\nEnter The Source:");
scanf("%d", &source);
printf("\nEnter The target");scanf("%d", &target);
co = dijsktra(cost,source,target);
printf("\nShortest Path: %d",co);getch();
}
int dijsktra(int cost[][N],int source,int target){
-
8/3/2019 DSA Manual
43/46
int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j;
char path[N];
for(i=1;i< N;i++){
dist[i] = IN;
prev[i] = -1;}
start = source;
selected[start]=1;dist[start] = 0;
while(selected[target] ==0)
{
min = IN;m = 0;
for(i=1;i< N;i++)
{
d = dist[start] +cost[start][i];if(d< dist[i]&&selected[i]==0)
{dist[i] = d;
prev[i] = start;
}
if(min>dist[i] && selected[i]==0){
min = dist[i];
m = i;}
}
start = m;selected[start] = 1;
}
start = target;j = 0;
while(start != -1)
{
path[j++] = start+65;start = prev[start];
}
path[j]='\0';strrev(path);
printf("%s", path);
return dist[target];}
OutputShortest Path Algorithm(DIJKSRTRA's ALGORITHMEnter the weight of the path between node 1 and 2: 2
-
8/3/2019 DSA Manual
44/46
Enter the weight of the path between node 1 and 3: 3
Enter the weight of the path between node 1 and 4: 4
Enter the weight of the path between node 1 and 5: 5Enter the weight of the path between node 2 and 3: 5
Enter the weight of the path between node 2 and 4: 2
Enter the weight of the path between node 2 and 5: 3Enter the weight of the path between node 3 and 4: 1
Enter the weight of the path between node 3 and 5: 4
Enter the weight of the path between node 4 and 5: 5Enter The Source:2
Enter The target4
CE
Shortest Path: 2
Ex No:10 Implement Knapsack Problem
Aim: To write a C program to implement Knapsack Problem .Algorithm
Step1:Get the number of Objects.Step2: Get the maximum capacity of Knapsack
Step3: Enter the weights and values of Objects.Step4:Fill the knapsack with maximum profit earned. But it should not exceed the capacity of the
knapsack.
Upper Bound=v+(W-w)(vi+1/w i+1)v-total value of items
W-knapsack capacity
w-total weight of items
Step5:Repeat the steps until the maximum profit is earned.
Program:
#include#includeint c,c1,n,i,j,k;
int q[10],X[10][10],W[10],P[10],max;
void get();void knapsack();
void display();
void get(){
printf("\nEnter the no.of objects:");
scanf("%d",&n);
printf("\nEnter the size of the knapsack:");scanf("%d",&c);
printf("\nEnter the weight and profit of objects:\n");
for(i=1;i
-
8/3/2019 DSA Manual
45/46
scanf("%d",&P[i]);
}
}void knapsack()
{
for(j=1;j
-
8/3/2019 DSA Manual
46/46
clrscr();
get();
knapsack();display();
getch();
}Output:Enter the no.of objects:4
Enter the size of the knapsack:12Enter the weight and profit of objects:
Enter the weight 1: 6
Enter the profit of weight:50
Enter the weight 2: 3Enter the profit of weight:26
Enter the weight 3: 9
Enter the profit of weight:84
Enter the weight 4: 4Enter the profit of weight:12
The optimal solution profit1 1 0 0 76
0 1 1 0 110
0 0 1 0 84
0 0 0 1 12The maximum profit is 110