0% found this document useful (0 votes)
19 views

Advanced Data Structures Lab Cse 2nd Year

Uploaded by

Bharathi Aishu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Advanced Data Structures Lab Cse 2nd Year

Uploaded by

Bharathi Aishu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

1

EX. NO : 1a
ARRAY IMPLEMENTATION OF STACK
DATE :

AIM:

To implement stack operations using array.

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 ;

Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

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

ARRAY IMPLEMENTATION OF QUEUE


DATE:

AIM :

To implement queue operations using array.

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 :

Queue using Array


1.Insertion
2.Deletion
3.Display
4.Exit
Enter the Choice:1

Enter no 1:10

Enter the Choice:1

Enter no 2:54

Enter the Choice:1

Enter no 3:98

Enter the Choice:1

Enter no 4:234

Enter the Choice:3

Queue Elements are:


10
54
98
234

Enter the Choice:2

Deleted Element is 10
Enter the Choice:3

Queue Elements are:


54
98
234

Enter the Choice:4


9

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);
}

void insertStart(struct Node** head, int data){

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

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

Linked List: 20 40 60 80 100


Deleted: 20
Deleted: 40

Linked List: 60 80 100


13

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>

using namespace std;

class Node {

public:

int data;

Node* link;

Node(int n)

this->data = n;

this->link = NULL;

};

class Stack {

Node* top;

public:

Stack() { top = NULL; }

void push(int data)

Node* temp = new Node(data);

if (!temp) {

cout << "\nStack Overflow";

exit(1);

temp->data = data;

temp->link = top;

top = temp;
16

bool isEmpty()

return top == NULL;

int peek()

if (!isEmpty())

return top->data;

else

exit(1);

void pop()

Node* temp;

if (top == NULL) {

cout << "\nStack Underflow" << endl;

exit(1);

else {

temp = top;

top = top->link;

free(temp);

void display()

{
17

Node* temp;

if (top == NULL) {

cout << "\nStack Underflow";

exit(1);

else {

temp = top;

while (temp != NULL) {

cout << temp->data;

temp = temp->link;

if (temp != NULL)

cout << " -> ";

};

int main()

Stack s;

s.push(11);

s.push(22);

s.push(33);

s.push(44);

s.display();

cout << "\nTop element is " << s.peek() << endl;

s.pop();
18

s.pop();

s.display();

cout << "\nTop element is " << s.peek() << endl;

return 0;

}
19

OUTPUT:

44 -> 33 -> 22 -> 11


Top element is 44
22 -> 11
Top element is 22
20

RESULT:
Thus operation on single linked list is performed.
21

Ex. No. 3b
LINKED LIST IMPLEMENTATION OF STACK
DATE:

AIM:

To implement stack 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
22

PROGRAM :

#include < stdio.h >


#include < stdlib.h >
struct node {
int data;
struct node * next;
};

struct node * front = NULL;


struct node * rear = NULL;
void enqueue(int value) {
struct node * ptr;
ptr = (struct node * ) malloc(sizeof(struct node));
ptr - > data = value;
ptr - > next = NULL;
if ((front == NULL) && (rear == NULL)) {
front = rear = ptr;
} else {
rear - > next = ptr;
rear = ptr;
}
printf("Node is Inserted\n\n");
}
int dequeue() {
if (front == NULL) {
printf("\nUnderflow\n");
return -1;
} else {
struct node * temp = front;
int temp_data = front - > data;
front = front - > next;
free(temp);
return temp_data;
}
}
void display() {
struct node * temp;
if ((front == NULL) && (rear == NULL)) {
printf("\nQueue is Empty\n");
} else {
printf("The queue is \n");
temp = front;
while (temp) {
printf("%d--->", temp - > data);
temp = temp - > next;
}
printf("NULL\n\n");
}
}
23

int main() {
int choice, value;

printf("\nImplementation of Queue using Linked List\n");


while (choice != 4) {
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
printf("\nEnter your choice : ");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", & value);
enqueue(value);
break;
case 2:
printf("Popped element is :%d\n", dequeue());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
return 0;
}
24

OUTPUT :

Enqueue Operation:

Implementation of Queue using Linked List


1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 1

Enter the value to insert: 12


Node is Inserted

1.Enqueue
2.Dequeue
3.Display
4.Exit

Enter your choice: 1

Enter the value to insert: 45


Node is Inserted

1.Enqueue
2.Dequeue
3.Display
4.Exit

Enter your choice: 1

Enter the value to insert: 56


Node is Inserted

1.Enqueue
2.Dequeue
3.Display
4.Exit

Enter your choice : 3


The queue is
12--->45--->56--->NULL
25

Dequeue Operation:

The queue is
12--->45--->56--->NULL

1.Enqueue
2.Dequeue
3.Display
4.Exit

Enter your choice: 2


Popped element is:12
1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 2


Popped element is:45
1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice : 3


The queue is
56--->NULL

1.Enqueue
2.Dequeue
3.Display
4.Exit

Enter your choice: 2


Popped element is:56
1. Enqueue
2. Dequeue
3. Display
4. Exit
26

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 :

/* 3c - Queue using Single Linked List */


#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch=0;
int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Queue using Linked List \n");
printf("1->Insert ");
printf("2->Delete ");
printf("3->View ")
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
/* Reorganize the links */
h = head;
while (h->next != NULL)
h = h->next;
h->next = temp;
temp->next = NULL;
break;

case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node deleted \n");
free(h);
break;
case 3:
29

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

h=head;
while (h->next!=NULL)
{

h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
41

OUTPUT :

Queue using Linked List


1->Insert 2->Delete 3->View 4->Exit Enter
your choice : 1

Enter label for new node : 12 Queue


using Linked List

1->Insert 2->Delete 3->View 4->Exit Enter


your choice : 1

Enter label for new node : 23 Queue


using Linked List

1->Insert 2->Delete 3->View 4->Exit Enter


your choice : 3

HEAD -> 12 -> 23 -> NULL


42

Result:
Thus the program of linked list using in queue has been executed successfully.
43

Ex. No. 4 APPLICATIONS OF LIST

Date: POLYNOMIAL ADDITION AND SUBTRACTION

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;

struct node * buildNode(int coefficient, int exponent) {


struct node *ptr = (struct node *) malloc(sizeof (struct node));
ptr->coefficient = coefficient;
ptr->exponent = exponent;
ptr->next = NULL;
return ptr;
}
void polynomial_insert(struct node ** myNode, int coefficient, int exponent) {
struct node *lPtr, *pPtr, *qPtr = *myNode;
lPtr = buildNode(coefficient, exponent);

if (*myNode == NULL || (*myNode)->exponent < exponent) {


*myNode = lPtr;
(*myNode)->next = qPtr;
return;
}
while (qPtr) {
pPtr = qPtr;
qPtr = qPtr->next;
if (!qPtr) {
pPtr->next = lPtr;
break;

}
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

if (temp->exponent > exponent && (!temp->next || temp->next->exponent < exponent)) {


x = buildNode(coefficient, exponent);
x->next = temp->next;
temp->next = x;
return;
}
temp = temp->next;
}
x->next = NULL;
temp->next = x;
}
}

void polynomial_multiply(struct node **n1, struct node *n2, struct node *n3) {
struct node * temp;
int coefficient, exponent;

temp = n3;

if (!n2 && !n3)


return;

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;
}

struct node * polynomial_deleteList(struct node *ptr) {


struct node *temp;
while (ptr){
temp = ptr->next;
free(ptr);
ptr = temp;
}
return NULL;
}
46

void polynomial_view(struct node *ptr) {


int i = 0;

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;
}

int main (int argc, char *argv[]) {


int coefficient, exponent, i, n;
int count;
printf("-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=\n");
printf(" Multiplication of Two Polynomials\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=\n");
printf("Enter the number of coefficients in the multiplicand:");
scanf("%d",&count);
for(i=0;i<count;i++){
printf("Enter the coefficient part:");
scanf("%d", &coefficient);
47

printf("Enter the exponent part:");


scanf("%d",&exponent);
polynomial_insert(&hPtr1, coefficient, exponent);
}

printf("Enter the number of coefficients in the multiplier:");


scanf("%d",&count);
for(i=0;i<count;i++){
printf("Enter the coefficient part:");
scanf("%d", &coefficient);
printf("Enter the exponent part:");
scanf("%d",&exponent);
polynomial_insert(&hPtr2, coefficient, exponent);
}
printf("Polynomial Expression 1: ");
polynomial_view(hPtr1);
printf("Polynomial Expression 2: ");
polynomial_view(hPtr2);

polynomial_multiply(&hPtr3, hPtr1, hPtr2);

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 :

Enter the expression :: 245+*


54

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 :

Enter the expression : (a+b)*c+(d-a)

ab+c*da-+
59

RESULT :
Thus the given postfix expression was evaluated using stack.
60

Ex. NO: 6

Date: IMPLEMENTATION OF BINARY SEARCH TREE

AIM :

To construct a binary search tree and perform search.

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 :

1. Get the element to be inserted.


2. Find the position in the tree where the element to be inserted by checkingthe elements in
the tree by traversing from the root.
3. If the element to be inserted is less than the element in the current node inthe tree then
traverse left sub tree
4. If the element to be inserted is greater than the element in the current node in the tree then
traverse right sub tree
5. Insert the element if there is no further move

Delete function :

1. Get the element to be deleted.


2. Find the node in the tree that contain the element.
3. Delete the node an rearrange the left and right siblings if any present for the deleted node
Find max function

1. Traverse the tree from the root.


2. Find the rightmost leaf node of the entire tree and return it
3. If the tree is empty return null. Find min
61

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;

struct node *left, *right;

};

struct node* newNode(int item)

struct node* temp

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

temp->key = item;

temp->left = temp->right = NULL;

return temp;

void inorder(struct node* root)

if (root != NULL) {

inorder(root->left);

printf("%d \n", root->key);

inorder(root->right);

struct node* insert(struct node* node, int key)

if (node == NULL)

return newNode(key);
63

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

return node;

int main()

struct node* root = NULL;

root = insert(root, 50);

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

Enter your Choice : 1 Enter an


element : 10

1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit

Enter your Choice : 1


Enter an element : 20
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit

Enter your Choice : 1 Enter an


element : 5
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 4 The smallest
Number is 5

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

Element not Found

1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit

Enter your Choice : 2 Enter an


element : 20

1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit

Enter your Choice : 6


20
10

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 :

A binary search tree x is called an AVL tree, if:


1. b(x .key) ∈ {−1, 0, 1}, and
2. x . left Child and x. right Child are both AVL trees. = the height balance of every node
must be -1, 0, or 1

insert/delete via standard algorithms


• after insert/delete: load balance b(node) might be changed to +2 or −2 for certain nodes
• re-balance load after each step

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 α.

1. Insertion into right sub tree of right child of α.


Inside Cases (require double rotation) :
2. Insertion into right sub tree of left child of α.
3. Insertion into left sub tree of right child of α.
The rebalancing is performed through four separate rotation algorithms.
You can either keep the height or just the difference in height, i.e. the balance factor; thishas to
be modified on the path of insertion even if you don't perform rotations
Once you have performed a rotation (single or double) you won't need to go back up the
tree
SINGLE ROTATION
Rotate From Right(n : reference node pointer)
{
p : node pointer;p := n.
right; n .right := p .left;
p. left := n;
n := p
}
68

DOUBLE ROTATION
Double Rotate From Right(n : reference node pointer)
{
Rotate From Left(n. right);
Rotate From Right(n);
}

INSERTION IN AVL TREES


Insert(T : tree pointer, x : element) :
{
if T = null then
T := new tree; T .data := x; height := 0;case
T .data = x : return ; //Duplicate do nothing T.
data > x : return Insert(T .left, x);
if ((height(T. left)- height(T .right)) = 2){if (T.
left. data > x ) then //outside case
T = Rotate from Left (T);else
//inside case
T = Double Rotate from Left (T);} T .data
< x : return Insert(T. right, x);code similar
to the left case End case
T. height := max(height(T. left),height(T. right)) +1;
return;
}

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;

struct Node *left;

struct Node *right;

int height;

};

int max(int a, int b);

int height(struct Node *N)

if (N == NULL)

return 0;

return 1+max(height(N->left), height(N->right));

int max(int a, int b)

return (a > b)? a : b;

struct Node* newNode(int key)

struct Node* node = (struct Node*)

malloc(sizeof(struct Node));

node->key = key;

node->left = NULL;
70

node->right = NULL;

node->height = 0; // new node is initially added at leaf

return(node);

struct Node *rightRotate(struct Node *y)

struct Node *x = y->left;

struct Node *T2 = x->right;

x->right = y;

y->left = T2;

y->height = height(y);

x->height = height(x);

return x;

struct Node *leftRotate(struct Node *x)

struct Node *y = x->right;

struct Node *T2 = y->left;

y->left = x;

x->right = T2;

x->height = height(x);

y->height = height(y);

return y;

int getBalance(struct Node *N)

{
71

if (N == NULL)

return 0;

return height(N->left) - height(N->right);

struct Node* insert(struct Node* node, int key)

if (node == NULL)

return(newNode(key));

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

else

return node;

node->height = height(node);

node to check whether this node became

unbalanced */

int balance = getBalance(node);

if (balance > 1 && key < node->left->key)

return rightRotate(node);

if (balance < -1 && key > node->right->key)

return leftRotate(node);

if (balance > 1 && key > node->left->key)

node->left = leftRotate(node->left);

return rightRotate(node);

}
72

if (balance < -1 && key < node->right->key)

node->right = rightRotate(node->right);

return leftRotate(node);

return node;

void preOrder(struct Node *root)

if(root != NULL)

printf("%d ", root->key);

preOrder(root->left);

preOrder(root->right);

int main()

struct Node *root = NULL;

root = insert(root, 10);

root = insert(root, 20);

root = insert(root, 30);

root = insert(root, 40);

root = insert(root, 50);

root = insert(root, 25);

printf("Preorder traversal of the constructed AVL"

" tree is \n");


73

preOrder(root);

return 0;

}
74

OUTPUT :

Preorder traversal of the constructed AVL tree is


30 20 10 25 40 50
75

RESULT :

Thus the implementation of AVL tree was demonstrated.


76

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.

max-priority queue and min-priority queue

 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.

There are mainly 4 operations we want from a priority queue:

1. Insert → To insert a new element in the queue.

2. Maximum/Minimum → To get the maximum and the minimum element from the
max-priority queue and min-priority queue respectively.

3. Extract Maximum/Minimum → To remove and return the maximum andthe


minimum element from the max-priority queue and min-priority queue respectively.

4. Increase/Decrease key → To increase or decrease key of any element in the


queue.
77

 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

void swap(int*, int*);


void display(int[],int);
void insert(int[],int,int,int);
int del_hi_priori(int[],int,int);

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;
}

void display(int a[],int n)


{
int i;
if(n==0)
{
printf("Queue Is Empty!!\n");
return;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
81

OUTPUT :

.....MAIN MENU.....

1.Insert.
2.Delete.
3.Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 5

.....MAIN MENU.....

1.Insert.
2.Delete.
3.Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 3

.....MAIN MENU.....

1.Insert.
2.Delete.
3.Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 2

.....MAIN MENU.....

1.Insert.
2.Delete.
3.Display.
4.Quit.

Enter your choice : 3

532

.....MAIN MENU.....

1.Insert.
82

2.Delete.
3.Display.
4.Quit.

Enter your choice : 2


The deleted value is : 5

.....MAIN MENU.....

1.Insert.
2.Delete.
3.Display.
4.Quit.

Enter your choice : 4


83

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:

The program of Implementation of Dijkstra's Algorithm created successfully.


88

Ex. No. 10
Implementation of prim's Algorithm
Date:

AIM:

To create the Implementation of prim's Algorithm.

ALGORITHM:

Step 1: Select a starting vertex.

Step 2: Repeat Steps 3 and 4 until there are fringe vertices.

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>

#define infinity 9999


#define MAX 20

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:

Enter no. of vertices:6

Enter the adjacency matrix:


031600
305030
150564
605002
036006
004260

spanning tree matrix:

031000
300030
100004
000002
030000
004200

Total cost of spanning tree=13


92

Result:

Thus the Implementation of prim's Algorithm created successfully.


93

Ex. No. 11
LINEAR SEARCH
Date:

AIM :

To perform linear search of an element on the given array.

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:

ENTER THE SIZE OF THE ARRAY:6


ENTER THE ELEMENTS OF THE ARRAY:
45
6
86
23
64
77
ENTER THE SEARCH KEY:86
____________________
1. LINEAR SEARCH
2. BINARY SEARCH
____________________
ENTER YOUR CHOICE:2
_____________________________________________
Location =3 Search_Key = 86 Found!
97

RESULT:

Thus an array was linearly searched for an element's existence .


98

Ex. No. 12a


INSERTION SORT
Date:

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 */

Enter number of elements


5
Enter 5 integers
37295
Sorted list in ascending order:
2
3
5
7
9

Test Case 2 – Best Case: Here, the elements are already sorted.

/* Best case */

Enter number of elements


3
Enter 3 integers
-3 31 66
Sorted list in ascending order:
-3
31
66

Test Case 3 – Worst Case: Here, the elements are reverse sorted.

/* Worst case */

Enter number of elements


5
Enter 5 integers
98631
Sorted list in ascending order:
1
3
6
8
9
101

RESULT:
Thus array elements was sorted using insertion sort.
102

Ex. No. 12b


SELECTION SORT
Date:

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>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
104

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

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.

8.Display the merge sorted array elements

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

Ex. No. 14a


LINEAR PROBING
Date:

AIM :
To Create an array of structure for linear probing.

ALGORITHM :

1. Create an array of structure (i.e a hash table).


2. Take a key and a value to be stored in hash table as input.
3. Corresponding to the key, an index will be generated i.e every key is stored in a particular
array index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into it and
increment the size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if necessary)
for free space to insert new data item.
Note: This probing will continue until we reach the same element again (from where we
began probing)
7. To display all the elements of hash table, element at each index is accessed (via for loop).
8. To remove a key from hash table, we will first calculate its index and delete it if key
matches, else probe through elements until we find key or an empty space where not a single
data has been entered (means data does not exist in the hash table).
9. Exit.
112

PROGRAM :

#include <bits/stdc++.h>
using namespace std;

void add_using_linear_probing(int hash[], int a)


{
int k = a % 10;
while (true) {
if (hash[k] == -1) {
hash[k] = a;
break;
}
k = (k + 1) % 10; //linear increment of probe
}
}

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_linear_probing(hash, a);
}
cout << "---------using linear 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;
}
113

OUTPUT :

---------using linear probing---------


Hash table is:
0->Empty
1->Empty
2->Empty
3->123
4->124
5->333
6->983
7->Empty
8->Empty
9->4679
114

RESULT :
Thus the linear probing program created successfully.
115

Ex. No. 14b


QUADRATIC PROBING
Date:

AIM :
To Create an array of structure for quadratic probing.

ALGORITHM :

Hash table is an array of size = TABLE_SIZE

Step 1: Read the value to be inserted, key

Step 2: let i = 0

Step 3: h key = key %TABLE_SIZE


Step 4: compute the index at which the value has to be inserted in hash table

index = (h key+ i * i) % TABLE_SIZE

Step 5: if there is no element at that index then insert the value at index and STOP

Step 6: If there is already an element at that index

step 4.1: i = i+1

step 7: if i < TABLE_SIZE then go to step 4

Algorithm to search a value in quadratic probing

Hash table is an array of size = TABLE_SIZE

Step 1: Read the value to be searched, key

Step 2: let i = 0

Step 3: h key = key % TABLE_SIZE


Step 4: compute the index at which the value can be found

index = (h key + i * i) % TABLE_SIZE

Step 5: if the element at that index is same as the search value then print element found and
STOP
116

Step 6: else

step 4.1: i = i+1

step 7: if i < TABLE_SIZE then go to step 4


117

PROGRAM :

#include <bits/stdc++.h>
using namespace std;

void add_using_quadratic_probing(int hash[], int a)


{
int k = a % 10;
int incr = 1;
while (true) {
if (hash[k] == -1) {
hash[k] = a;
break;
}
k = (k + int(pow(incr, 2))) % 10;
incr++;
}
}

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 :

---------using quadratic probing---------


Hash table is:
0->Empty
1->Empty
2->Empty
3->123
4->124
5->Empty
6->Empty
7->983
8->333
9->4679
119

RESULT :
Thus the quadratic probing program created successfully.

You might also like