Advanced Data Structures Lab Cse 2nd Year
Advanced Data Structures Lab Cse 2nd Year
EX. NO : 1a
ARRAY IMPLEMENTATION OF STACK
DATE :
AIM:
ALGORITHM :
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. If top < max -1
8. Increment top
9. Store element at current position of top
10. Else
11. Print Stack overflow
12. If choice = 2 then
13. If top < 0 then
14. Print Stack underflow
15. Else
16. Display current top element
17. Decrement top
18. If choice = 3 then
19. Display stack elements starting from top
20. Stop.
2
PROGRAM :
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
3
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}
4
OUTPUT ;
98
24
12
Press Next Choice
Enter the Choice:2
24
12
Press Next Choice
Enter the Choice:4
5
RESULT :
Thus push and pop operations of a stack was demonstrated using arrays
6
EX. No: 1b
AIM :
ALGORITHM :
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
7. If rear < max -1
8. Increment rear
9. Store element at current position of rear
10. Else
11. Print Queue Full
12. If choice = 2 then
13. If front = –1 then
14. Print Queue empty
15. Else
16. Display current front element
17. Increment front
18. If choice = 3 then
19. Display queue elements starting from front to rear.
20. Stop
7
PROGRAM :
#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
print f("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
print f("\n Queue is empty");
}
else
{
print f("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
print f("\nQueue Elements are:\n ");
if(front==rear)
print f("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
print f("%d",queue[i]);
print f("\n");
}
break;
case 4:
exit(0);
default:
print f("Wrong Choice: please see the options");
}}}
return 0;
}
8
OUTPUT :
Enter no 1:10
Enter no 2:54
Enter no 3:98
Enter no 4:234
Deleted Element is 10
Enter the Choice:3
RESULT :
Thus insert and delete operations of a queue was demonstrated using arrays.
10
Ex. No. 2
ARRAY IMPLEMENTATION OF LIST
DATE:
AIM :
To create a list using array and perform operations such as display, insertions
and deletions.
ALGORITHM :
1. Start
2. Define list using an array of size n.
3. First item with subscript or position = 0
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create an empty location in array after the node by moving the existing elements one
position ahead.
9. Insert the new element at appropriate position
10. Else if choice = 2
11. Get element to be deleted.
12. Locate the position of the element replace the element with the element in the
following position.
13. Repeat the step for successive elements until end of the array.
14. Else
15. Traverse the list from position or subscript 0 to n.
16. Stop
11
PROGRAM :
#include<stdlib.h>
#include<stdio.h>
struct Node{
int data;
struct Node *next;
};
void deleteStart(struct Node** head){
struct Node* temp = *head;
if(*head == NULL){
printf("Impossible to delete from empty Singly Linked List");
return;
}
*head = (*head)->next;
printf("Deleted: %d\n", temp->data);
free(temp);
}
newNode->data = data;
newNode->next = *head;
*head = newNode;
printf("Inserted %d\n",newNode->data);
}
void display(struct Node* node){
printf("\nLinked List: ");
while(node!=NULL){
printf("%d ",node->data);
node = node->next;
}
printf("\n");
}
int main()
{
struct Node* head = NULL;
insertStart(&head,100);
insertStart(&head,80);
insertStart(&head,60);
insertStart(&head,40);
insertStart(&head,20);
display(head);
deleteStart(&head);
deleteStart(&head);
display(head)
return 0;
}
12
OUTPUT:
Inserted 100
Inserted 80
Inserted 60
Inserted 40
Inserted 20
RESULT:
Thus the array implementation of list was demonstrated.
14
Ex. No. 3a
LINKED LIST IMPLEMENTATION OF LIST
DATE: [SINGLY LINKED LIST]
AIM:
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.
ALGORITHM :
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
9. Insert the new node at appropriate position by manipulating address
10. Else if choice = 2
11. Get node's data to be deleted.
12. Locate the node and delink the node
13. Rearrange the links
14. Else
15. Traverse the list from Head node to node which points to null
16. Stop
15
PROGRAM :
#include <bits/stdc++.h>
class Node {
public:
int data;
Node* link;
Node(int n)
this->data = n;
this->link = NULL;
};
class Stack {
Node* top;
public:
if (!temp) {
exit(1);
temp->data = data;
temp->link = top;
top = temp;
16
bool isEmpty()
int peek()
if (!isEmpty())
return top->data;
else
exit(1);
void pop()
Node* temp;
if (top == NULL) {
exit(1);
else {
temp = top;
top = top->link;
free(temp);
void display()
{
17
Node* temp;
if (top == NULL) {
exit(1);
else {
temp = top;
temp = temp->link;
if (temp != NULL)
};
int main()
Stack s;
s.push(11);
s.push(22);
s.push(33);
s.push(44);
s.display();
s.pop();
18
s.pop();
s.display();
return 0;
}
19
OUTPUT:
RESULT:
Thus operation on single linked list is performed.
21
Ex. No. 3b
LINKED LIST IMPLEMENTATION OF STACK
DATE:
AIM:
ALGORITHM :
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
11. Make temp node point to first node
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
15. Display stack elements starting from head node till null
16. Stop
22
PROGRAM :
int main() {
int choice, value;
OUTPUT :
Enqueue Operation:
1.Enqueue
2.Dequeue
3.Display
4.Exit
1.Enqueue
2.Dequeue
3.Display
4.Exit
1.Enqueue
2.Dequeue
3.Display
4.Exit
Dequeue Operation:
The queue is
12--->45--->56--->NULL
1.Enqueue
2.Dequeue
3.Display
4.Exit
1.Enqueue
2.Dequeue
3.Display
4.Exit
RESULT:
Thus push and pop operations of a stack was demonstrated using linked list.
27
Ex. No. 3c
LINKED LIST IMPLEMENTATION OF QUEUE
DATE:
AIM :
To implement queue operations using linked list.
ALGORITHM :
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
11. Make temp node point to first node
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
15. Display stack elements starting from head node till null
16. Stop
28
PROGRAM :
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node deleted \n");
free(h);
break;
case 3:
29
h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
41
OUTPUT :
Result:
Thus the program of linked list using in queue has been executed successfully.
43
AIM :
To store a polynomial using linked list. Also, perform addition and subtraction on two
polynomials.
ALGORITHM :
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator‟s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the inputoperator, Pop it
from the stack and print it.
9. Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
12. If the character is a right parenthesis, pop all the operators from the stack andprint it until a
left parenthesis is encountered. Do not print the parenthesis.
44
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct node {
int coefficient, exponent;
struct node *next;
};
struct node *hPtr1, *hPtr2, *hPtr3;
}
else if ((exponent < pPtr->exponent) && (exponent > qPtr->exponent){
lPtr->next = qPtr;
pPtr->next = lPtr;
break;
}
}
return;
}
void polynomial_add(struct node **n1, int coefficient, int exponent) {
struct node *x = NULL, *temp = *n1;
if (*n1 == NULL || (*n1)->exponent < exponent) {
*n1 = x = buildNode(coefficient, exponent);
(*n1)->next = temp;
} else {
while (temp) {
if (temp->exponent == exponent) {
temp->coefficient = temp->coefficient + coefficient;
return;
45
void polynomial_multiply(struct node **n1, struct node *n2, struct node *n3) {
struct node * temp;
int coefficient, exponent;
temp = n3;
if (!n2) {
*n1 = n3;
} else if (!n3) {
*n1 = n2;
} else {
while (n2) {
while (n3) {
coefficient = n2->coefficient * n3->coefficient;
exponent = n2->exponent + n3->exponent;
n3 = n3->next;
polynomial_add(n1, coefficient, exponent);
}
n3 = temp;
n2 = n2->next;
}
}
return;
}
int flag=0;
while (ptr) {
if(ptr->exponent != 0 || ptr->exponent != 1 ){
if(ptr->coefficient > 0 && flag==0 ){
printf("%dx^%d", ptr->coefficient,ptr->exponent);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%dx^%d", ptr->coefficient,ptr->exponent);
else if(ptr->coefficient < 0)
printf("%dx^%d", ptr->coefficient,ptr->exponent);
}
else if (ptr->exponent == 0){
if(ptr->coefficient > 0 && flag==0 ){
printf("%d", ptr->coefficient);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%d", ptr->coefficient);
else if(ptr->coefficient < 0)
printf("%d", ptr->coefficient);
}
else if( ptr->exponent == 1 ){
if(ptr->coefficient > 0 && flag==0 ){
printf("%dx", ptr->coefficient);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%dx", ptr->coefficient);
else if(ptr->coefficient < 0)
printf("%dx", ptr->coefficient);
}
ptr = ptr->next;
i++;
}
printf("\n");
return;
}
printf("Output:\n");
polynomial_view(hPtr3);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
hPtr1 = polynomial_deleteList(hPtr1);
hPtr2 = polynomial_deleteList(hPtr2);
hPtr3 = polynomial_deleteList(hPtr3);
return 0;
48
OUTPUT :
=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=–=
Multiplication of Two Polynomials
-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=–=
Enter the number of coefficients in the multiplicand:2
Enter the coefficient part:3
Enter the exponent part:2
Enter the coefficient part:2
Enter the exponent part:3
Enter the number of coefficients in the multiplier:2
Enter the coefficient part:4
Enter the exponent part:2
Enter the coefficient part:1
Enter the exponent part:3
Polynomial Expression 1: 2x^3+3x^2
Polynomial Expression 2: 1x^3+4x^2
Output:
2x^6+11x^5+12x^4
-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
49
RESULT :
Thus application of list for polynomial manipulation was demonstrated.
50
Ex. No. 5a
INFIX TO POSTFIX
Date:
AIM :
To convert infix expression to its postfix form using stack operations.
ALGORITHM :
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator’s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the inputoperator, Pop it
from the stack and print it.
9. Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
If the character is a right parenthesis, pop all the operators from the stack and print it until a left
parenthesis is encountered. Do not print the parenthesis
51
Program:
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
52
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
The result of expression 245+* = 18
53
OUTPUT :
RESULT:
Thus the given infix expression was converted into postfix form using stack.
55
Ex. No. 5b
EXPRESSION EVALUATION
Date:
AIM :
To evaluate the given postfix expression using stack operations.
ALGORITHM :
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
5. If character is an operand push it onto the stack
6. If character is an operator
7. Pop topmost two elements from stack.
8. Apply operator on the elements and push the result onto the stack,
Eventually only result will be in the stack at end of the expression.
9. Pop the result and print it.
56
PROGRAM :
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
57
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
58
OUTPUT :
ab+c*da-+
59
RESULT :
Thus the given postfix expression was evaluated using stack.
60
Ex. NO: 6
AIM :
ALGORITHM :
1. Start
2. Call insert to insert an element into binary search tree.
3. Call delete to delete an element from binary search tree.
4. Call find max to find the element with maximum value in binary search tree
5. Call find min to find the element with minimum value in binary search tree
6. Call find to check the presence of the element in the binary search tree
7. Call display to display the elements of the binary search tree
8. Call make empty to delete the entire tree.
9. Stop
Insert function :
Delete function :
function
1. Traverse the tree from the root.
2. Find the leftmost leaf node of the entire tree and return it
3. If the tree is empty return null. Find
function
1. Traverse the tree from the root.
2. Check whether the element to searched matches with element of the currentnode. If match
occurs return it.
3. Otherwise if the element is less than that of the element of the current nodethen search the
leaf sub tree.
4. Else search right sub tree.Make
empty function
Make the root of the tree to point to null.
62
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
};
temp->key = item;
return temp;
if (root != NULL) {
inorder(root->left);
inorder(root->right);
if (node == NULL)
return newNode(key);
63
return node;
int main()
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
}
64
OUTPUT :
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 3 Enter an
element : 100
65
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 7
66
RESULT :
The program for binary search tree is executed and verified.
67
Ex. No. 7
IMPLEMENTATION OF AVL TREES
Date:
AIM :
To implement AVL Trees.
ALGORITHM :
Insert operation may cause balance factor to become 2 or –2 for some node
› only nodes on the path from insertion point to root node have possibly changed in height
› So after the Insert, go back up to the root node by node, updating heights
› If a new balance factor (the difference h left – h right ) is 2 or –2, adjust tree by rotation
around the node
Let the node that needs rebalancing be α.
There are 4 cases:
Outside Cases (require single rotation) :
Insertion into left sub tree of left child of α.
DOUBLE ROTATION
Double Rotate From Right(n : reference node pointer)
{
Rotate From Left(n. right);
Rotate From Right(n);
}
DELETION
Similar but more complex than insertion
› Rotations and double rotations needed to rebalance
› Imbalance may propagate upward so that many rotations may be needed.
69
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct Node
int key;
int height;
};
if (N == NULL)
return 0;
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
70
node->right = NULL;
return(node);
x->right = y;
y->left = T2;
y->height = height(y);
x->height = height(x);
return x;
y->left = x;
x->right = T2;
x->height = height(x);
y->height = height(y);
return y;
{
71
if (N == NULL)
return 0;
if (node == NULL)
return(newNode(key));
else
return node;
node->height = height(node);
unbalanced */
return rightRotate(node);
return leftRotate(node);
node->left = leftRotate(node->left);
return rightRotate(node);
}
72
node->right = rightRotate(node->right);
return leftRotate(node);
return node;
if(root != NULL)
preOrder(root->left);
preOrder(root->right);
int main()
preOrder(root);
return 0;
}
74
OUTPUT :
RESULT :
Ex. No. 8
IMPLEMENTATION OF HEAP USING PRIORITY QUEUES
Date:
AIM :
To Implementation Of Heap Using Priority Queues.
ALGORITHM :
Priority queue is a type of queue in which every element has a key associated to it
and the queue returns the element according to these keys, unlike the traditional queue
which works on first come first serve basis.
Thus, a max-priority queue returns the element with maximum key first whereas, a
min-priority queue returns the element with the smallest keyfirst.
Priority queues are used in many algorithms like Huffman Codes, Prim's algorithm,
etc. It is also used in scheduling processes for a computer, etc.
Heaps are great for implementing a priority queue because of the largest and
smallest element at the root of the tree for a max-heap and a min- heap
respectively. We use a max-heap for a max-priority queue and a min-heap for a
min-priority queue.
2. Maximum/Minimum → To get the maximum and the minimum element from the
max-priority queue and min-priority queue respectively.
A priority queue stores its data in a specific order according to the keys of
the elements. So, inserting a new data must go in a place according to the
specified order. This is what the insert operation does.
The entire point of the priority queue is to get the data according to
thekey of the data and the Maximum/Minimum and Extract
Maximum/Minimum does this for us.
We know that the maximum (or minimum) element of a priority queue is
at the root of the max-heap (or min-heap). So, we just need to return the
element at the root of the heap.
This is like the pop of a queue, we return the element as well as delete it
from the heap. So, we have to return and delete the root of a heap. Firstly,
we store the value of the root in a variable to return it later from the
function and then we just make the root equal to the last element of the
heap. Now the root is equal to the last element of the heap, we delete the
last element easily by reducing the size of the heap by 1.
Doing this, we have disturbed the heap property of the root but we have
not touched any of its children, so they are still heaps. So, we can call
Heapify on the root to make the tree a heap again.
78
PROGRAM :
#include<stdio.h>
#include<math.h>
#define MAX 100
int main()
{
int lb,choice,num,n,a[MAX],data,s;
choice = 0;
n=0;
lb=0;
while(choice != 4)
{
printf(".....MAIN MENU.....\n");
printf("\n1.Insert.\n");
printf("2.Delete.\n");
printf("3.Display.\n");
printf("4.Quit.\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter data to be inserted : ");
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("The deleted value is : %d",s);
if(n>0)
n--;
break;
case 3:
printf("\n");
display(a,n);
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
79
printf("\n\n");
}
return 0;
}
void insert(int a[],int heapsize,int data,int lb)
{
int i,p;
int parent(int);
if(heapsize==MAX)
{
printf("Queue Is Full!!n");
return;
}
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}
int del_hi_priori(int a[],int heapsize,int lb)
{
int data,i,l,r,max_child,t;
int left(int);
int right(int);
if(heapsize==1)
{
printf("Queue Is Empty!!\n");
return 0;
}
t=a[lb];
swap(&a[lb],&a[heapsize-1]);
i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
else
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child])
break;
swap(&a[i],&a[max_child]);
i=max_child;
}
return t;
}
80
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
int left(int i)
{
return 2*i+1;
}
int right(int i)
{
return 2*i+2;
}
OUTPUT :
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
532
.....MAIN MENU.....
1.Insert.
82
2.Delete.
3.Display.
4.Quit.
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
RESULT:
Thus the implementation heap using priority queue was demonstrated.
84
Ex. No. 9
Implementation of Dijkstra's Algorithm
Date:
AIM :
To start the program of Implementation of Dijkstra's Algorithm.
ALGORITHM :
1. start the program.
2. To find the shortest path in algorithm.
3. Mark the ending vertex with a distance of zero. Designate this vertex as
current.
4. Find all vertices leading to the current vertex. Calculate their distances to the
end. .
5. Mark the current vertex as visited.
6. Mark the vertex with the smallest distance as current, and repeat from step 4.
7. stop the program.
85
PROGRAM :
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source
");
for (int i = 0; i < V; i++)
printf("%d \t %d
", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0; }
86
OUTPUT :
Vertex Distance from Source
00
16
2 14
3 21
4 21
5 11
69
78
8 15
87
RESULT:
Ex. No. 10
Implementation of prim's Algorithm
Date:
AIM:
ALGORITHM:
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum
weight.
Step 4: Add the selected edge and the vertex to the minimum spanning tree T.
[END OF LOOP]
Step 5: EXIT.
89
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
90
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
91
Output:
031000
300030
100004
000002
030000
004200
Result:
Ex. No. 11
LINEAR SEARCH
Date:
AIM :
ALGORITHM :
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
7. If Ai =
search
then
found = 1
Print
"Element
found"
Print
position i
Stop
8. If found = 0 then
print
"Element not
found"Stop
94
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
main()
{
int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int n);
clrscr();
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);
printf("___________________\n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf("___________________\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
return 0;
}
void linear_search(int search_key,int array[100],int n)
{
int i,location;
for(i=1;i<=n;i++)
{
if(search_key == array[i])
{
location = i;
printf("______________________________________\n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf("______________________________________\n");
95
}
}
}
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high;
low = 1;
high = n;
mid = (low + high)/2;
i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1;
high = mid+1;
mid = (low+high)/2;
}
else
{
low = mid+1;
high = n;
mid = (low+high)/2;
}
}
printf("__________________________________\n");
printf("location=%d\t",mid);
printf("Search_Key=%d Found!\n",search_key);
printf("__________________________________\n");
}
96
OUTPUT:
RESULT:
AIM :
To sort an array of N numbers using Insertion sort.
ALGORITHM :
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer index i varies from second element to last element
5. Inner index j is used to compare elements to left of outer index
6. Insert the element into the appropriate position.
7. Display the array elements after each pass
8. Display the sorted array elements.
9. Stop
99
PROGRAM :
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
100
OUTPUT :
Test Case 1 – Average Case: Here, the elements are entered in random order.
/* Average case */
Test Case 2 – Best Case: Here, the elements are already sorted.
/* Best case */
Test Case 3 – Worst Case: Here, the elements are reverse sorted.
/* Worst case */
RESULT:
Thus array elements was sorted using insertion sort.
102
AIM :
To sort an array of N numbers using Merge sort.
ALGORITHM ;
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Display both sorted sub-arrays
7. Merge the sorted sub-arrays onto a single sorted array.
103
PROGRAM :
#include <stdio.h>
OUTPUT :
Sorted array:
11 12 22 25 64
105
RESULT :
Thus array elements was sorted using selection sort's divide and conquer method.
106
Ex. No. 13
MERGE SORT
Date:
AIM :
To sort an array of N numbers using Merge sort.
ALGORITHM :
1.Start
2.Read number of array elements n
9.Stop
107
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0; // Initial index of first subarray
j = 0; // Initial index of second
subarray
k = l; // Initial index of merged
subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
108
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) /
sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
109
OUTPUT :
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
110
RESULT :
Thus array elements was sorted using merge sort's divide and conquer method.
111
AIM :
To Create an array of structure for linear probing.
ALGORITHM :
PROGRAM :
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr{ 123, 124, 333, 4679, 983 };
OUTPUT :
RESULT :
Thus the linear probing program created successfully.
115
AIM :
To Create an array of structure for quadratic probing.
ALGORITHM :
Step 2: let i = 0
Step 5: if there is no element at that index then insert the value at index and STOP
Step 2: let i = 0
Step 5: if the element at that index is same as the search value then print element found and
STOP
116
Step 6: else
PROGRAM :
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr{ 123, 124, 333, 4679, 983 };
int hash[10]; //size of hashtable is 10
memset(hash, -1, sizeof(hash)); //initialize with empty initially
for (int a : arr) {
add_using_quadratic_probing(hash, a);
}
cout << "---------using quadratic probing---------\n";
cout << "Hash table is:\n";
for (int i = 0; i < 10; i++) {
if (hash[i] == -1)
cout << i << "->"
<< "Empty" << endl;
else
cout << i << "->" << hash[i] << endl;
}
return 0;
}
118
OUTPUT :
RESULT :
Thus the quadratic probing program created successfully.