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

DSA Practical File

The document contains code to implement stack and queue data structures using arrays and linked lists in C programming language. For stacks, it includes push, pop and display functions. For queues, it includes enqueue, dequeue and display functions. The code is tested and output is displayed showing insertion and removal of elements from the stack and queue.

Uploaded by

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

DSA Practical File

The document contains code to implement stack and queue data structures using arrays and linked lists in C programming language. For stacks, it includes push, pop and display functions. For queues, it includes enqueue, dequeue and display functions. The code is tested and output is displayed showing insertion and removal of elements from the stack and queue.

Uploaded by

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

Q1. Write programs to implement the following using an array.

a) Stack ADT
b) Queue ADT

Ans.a) Stack ADT

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
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)");
}

Page | 1 Ashwani kumar


220530122007
}
while(choice!=4);
return 0;
}
void push()
{
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");
}
}

Page | 2 Ashwani kumar


220530122007
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

EXIT POINT

Page | 3 Ashwani kumar


220530122007
b) Queue ADT

#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)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;

Page | 4 Ashwani kumar


220530122007
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

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

Page | 5 Ashwani kumar


220530122007
2. Write programs to implement the following using a singly linked list.
a) Stack ADT
b) Queue ADT

Ans.a) Stack ADT

#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;

int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)

Page | 6 Ashwani kumar


220530122007
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
top = NULL;
}
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;

Page | 7 Ashwani kumar


220530122007
}
void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}

while (top1 != NULL)


{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
void pop()
{
top1 = top;

if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
int topelement()
{
return(top->info);
}
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
void destroy()
{
top1 = top;

while (top1 != NULL)


{
top1 = top->ptr;

Page | 8 Ashwani kumar


220530122007
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;

printf("\n All stack elements destroyed");


count = 0;
}

Output:

1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Display
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56

Enter choice : 1
Enter data : 80

Enter choice : 2

Popped value : 80
Enter choice : 3

Top element : 56
Enter choice : 1
Enter data : 78

Enter choice : 1
Enter data : 90

Enter choice : 6
907856
Enter choice : 7

No. of elements in stack : 3


Enter choice : 8

All stack elements destroyed

Page | 9 Ashwani kumar


220530122007
Enter choice : 4

Stack is empty
Enter choice : 5

b) Queue ADT

#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)

Page | 10 Ashwani kumar


220530122007
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
void display()
{
front1 = front;

Page | 11 Ashwani kumar


220530122007
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");

Page | 12 Ashwani kumar


220530122007
}

Output:

1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
Enter choice : 1
Enter data : 14

Enter choice : 1
Enter data : 85

Enter choice : 1
Enter data : 38

Enter choice : 3
Front element : 14
Enter choice : 6
148538
Enter choice : 7

Queue size : 3
Enter choice : 2

Dequed value : 14
Enter choice : 6
8538
Enter choice : 7

Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5

Page | 13 Ashwani kumar


220530122007
3. Write a program to implement the deque (double-ended queue) ADT using a doubly linked list.

Ans.

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *prev, *next;
};
struct node *head = NULL, *tail = NULL;
struct node * createNode(int data)
{
struct node *newnode = (struct node *)malloc(sizeof (struct node));
newnode->data = data;
newnode->next = newnode->prev = NULL;
return (newnode);
}
void createSentinels()
{
head = createNode(0);
tail = createNode(0);
head->next = tail;
tail->prev = head;
}
void enqueueAtFront(int data)
{
struct node *newnode, *temp;
newnode = createNode(data);
temp = head->next;
head->next = newnode;
newnode->prev = head;
newnode->next = temp;
temp->prev = newnode;
}

void enqueueAtRear(int data)


{
struct node *newnode, *temp;
newnode = createNode(data);
temp = tail->prev;
tail->prev = newnode;
newnode->next = tail;
newnode->prev = temp;
temp->next = newnode;
}
void dequeueAtFront()
{
struct node *temp;
if (head->next == tail)

Page | 14 Ashwani kumar


220530122007
{
printf("Queue is empty\n");
}
else
{
temp = head->next;
head->next = temp->next;
temp->next->prev = head;
free(temp);
}
return;
}
void dequeueAtRear()
{
struct node *temp;
if (tail->prev == head)
{
printf("Queue is empty\n");
}
else
{
temp = tail->prev;
tail->prev = temp->prev;
temp->prev->next = tail;
free(temp);
}
return;
}
void display()
{
struct node *temp;

if (head->next == tail)
{
printf("Queue is empty\n");
return;
}
temp = head->next;
while (temp != tail)
{
printf("%-3d", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
int data, ch;
createSentinels();
while (1)

Page | 15 Ashwani kumar


220530122007
{
printf("1. Enqueue at front\n2. Enqueue at rear\n");
printf("3. Dequeue at front\n4. Dequeue at rear\n");

printf("5. Display\n6. Exit\n");


printf("Enter your choice:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter the data to insert:");
scanf("%d", &data);
enqueueAtFront(data);
break;
case 2:
printf("Enter ur data to insert:");
scanf("%d", &data);
enqueueAtRear(data);
break;
case 3:
dequeueAtFront();
break;
case 4:
dequeueAtRear();
break;
case 5:
display();
break;
case 6:
exit(0);
default:
printf(" enter correct option\n");
break;
}
}
return 0;
}
Output:

Page | 16 Ashwani kumar


220530122007
4. Write a program to perform the following operations:
a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.

Ans.a) Insert an element into a binary search tree

#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 ", root->key);
inorder(root->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);
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;
}
Output:
20 30 40 50 60 70 80

Page | 17 Ashwani kumar


220530122007
b) Delete an element from a binary search tree

#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 ", root->key);
inorder(root->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
node->right = insert(node->right, key);
return node;
}
struct node * minValueNode(struct node* node) {
struct node* current = node;
while (current->left != NULL)
current = current->left;

return current;
}
struct node* deleteNode(struct node* root, int key) {
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if (root->left == NULL) {
struct node *temp = root->right;
free(root);
return temp;

Page | 18 Ashwani kumar


220530122007
} else if (root->right == NULL) {
struct node *temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
int main() {
struct node *root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);
return 0;
}

Output:

Inorder traversal of the given tree


20 30 40 50 60 70 80
Delete 20
Inorder traversal of the modified tree
30 40 50 60 70 80
Delete 30
Inorder traversal of the modified tree
40 50 60 70 80
Delete 50
Inorder traversal of the modified tree
40 60 70 80

Page | 19 Ashwani kumar


220530122007
c) Search for a key element in a binary search tree

#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode *leftChildNode;
struct TreeNode *rightChildNode;
};
typedef struct TreeNode node;
node *rootNode = NULL;
void insertNode(int i, node **n) {
if (*n == NULL) {
(*n) = (node*)malloc(sizeof(node));
(*n)->leftChildNode = NULL;
(*n)->rightChildNode = NULL;
(*n)->data = i;
}
else if ((*n)->data == i)
printf("\nThis value already exists in the tree!");
else if (i> (*n)->data)
insertNode(i, &((*n)->rightChildNode));
else
insertNode(i, &((*n)->leftChildNode));
}
void searchNode(int i, node **n) {
if (*n == NULL)
printf("\nValue does not exist in tree!");
else if((*n)->data == i)
printf("\nValue found!");
else if(i> (*n)->data)
searchNode(i, &((*n)->rightChildNode));
else
searchNode(i, &((*n)->leftChildNode));
}
int main()
{
int ch, num, num1;
do {
printf("\nSelect a choice from the menu below.");
printf("\n1. Insert a node.");
printf("\n2. Search for a node.");
printf("\nChoice: ");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("\nEnter an element: ");
scanf("%d", &num);
insertNode(num, &rootNode);
break;
case 2:

Page | 20 Ashwani kumar


220530122007
printf("\nEnter the element to be searched for: ");
scanf("%d", &num);
searchNode(num, &rootNode);
break;
default:
exit(0);
}
printf("\nIf you want to return to the menu, press 1.");
printf("\nChoice: ");
scanf("%d", &num);
} while(num == 1);
return 0;
}

Output:

Select a choice from the menu below.


1. Insert a node.
2. Search for a node.
Choice: 1
Enter an element: 65
If you want to return to the menu, press 1.
Choice: 1
Select a choice from the menu below.
1. Insert a node.
2. Search for a node.
Choice: 1
Enter an element: 21
If you want to return to the menu, press 1.
Choice: 1
Select a choice from the menu below.
1. Insert a node.
2. Search for a node.
Choice: 2
Enter the element to be searched for: 65
Value found!
If you want to return to the menu, press 1.
Choice: 2

Page | 21 Ashwani kumar


220530122007
5. Write a program to implement circular queue ADT using an array.

Ans.

#include<stdio.h>
#define capacity 6
int queue[capacity];
int front = -1, rear = -1;
int checkFull ()
{
if ((front == rear + 1) || (front == 0 && rear == capacity - 1))
{
return 1;
}
return 0;
}
int checkEmpty ()
{
if (front == -1)
{
return 1;
}
return 0;
}
void enqueue (int value)
{
if (checkFull ())
printf ("Overflow condition\n");
else
{
if (front == -1)
front = 0;
rear = (rear + 1) % capacity;
queue[rear] = value;
printf ("%d was enqueued to circular queue\n", value);
}
}
int dequeue ()
{
int variable;
if (checkEmpty ())
{
printf ("Underflow condition\n");
return -1;
}
else
{
variable = queue[front];
if (front == rear)
{
front = rear = -1;

Page | 22 Ashwani kumar


220530122007
}
else
{
front = (front + 1) % capacity;
}
printf ("%d was dequeued from circular queue\n", variable);
return 1;
}
}
void print ()
{
int i;
if (checkEmpty ())
printf ("Nothing to dequeue\n");
else
{
printf ("\nThe queue looks like: \n");
for (i = front; i != rear; i = (i + 1) % capacity)
{
printf ("%d ", queue[i]);
}
printf ("%d \n\n", queue[i]);
}
}
int main ()
{
dequeue ();
enqueue (15);
enqueue (20);
enqueue (25);
enqueue (30);
enqueue (35);
print ();
dequeue ();
dequeue ();
print ();
enqueue (40);
enqueue (45);
enqueue (50);
enqueue (55);
print ();
return 0;
}

Output:

Underflow condition
15 was enqueued to circular queue
20 was enqueued to circular queue
25 was enqueued to circular queue
30 was enqueued to circular queue

Page | 23 Ashwani kumar


220530122007
35 was enqueued to circular queue

The queue looks like:


15 20 25 30 35

15 was dequeued from circular queue


20 was dequeued from circular queue

The queue looks like:


25 30 35

40 was enqueued to circular queue


45 was enqueued to circular queue
50 was enqueued to circular queue
Overflow condition

The queue looks like:


25 30 35 40 45 50

Page | 24 Ashwani kumar


220530122007
6. Write a program to implement all the functions of a dictionary (ADT) using hashing.
Ans.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
typedef struct Node {
char key[50];
char value[100];
struct Node* next;
} Node;
typedef struct Dictionary {
Node* table[SIZE];
} Dictionary;
unsigned int hashFunction(char* key) {
unsigned int hash = 0;
for (int i = 0; key[i] != '\0'; i++) {
hash = hash * 31 + key[i];
}
return hash % SIZE;
}
Dictionary* createDictionary() {
Dictionary* dict = (Dictionary*)malloc(sizeof(Dictionary));
for (int i = 0; i< SIZE; i++) {
dict->table[i] = NULL;
}
return dict;
}
void insert(Dictionary* dict, char* key, char* value) {
unsigned int index = hashFunction(key);
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->key, key);
strcpy(newNode->value, value);
newNode->next = dict->table[index];
dict->table[index] = newNode;
}
Node* search(Dictionary* dict, char* key) {
unsigned int index = hashFunction(key);
Node* temp = dict->table[index];
while (temp != NULL) {
if (strcmp(temp->key, key) == 0) {
return temp;
}
temp = temp->next;
}
return NULL;
}
void deleteNode(Dictionary* dict, char* key) {
unsigned int index = hashFunction(key);
Node* current = dict->table[index];

Page | 25 Ashwani kumar


220530122007
Node* prev = NULL;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
if (prev != NULL) {
prev->next = current->next;
} else {
dict->table[index] = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
void display(Dictionary* dict) {
for (int i = 0; i< SIZE; i++) {
Node* temp = dict->table[i];
while (temp != NULL) {
printf("Key: %s, Value: %s\n", temp->key, temp->value);
temp = temp->next;
}
}
}
int main() {
Dictionary* dict = createDictionary();
insert(dict, "name", "John");
insert(dict, "age", "25");
insert(dict, "city", "New York");
printf("Initial Dictionary:\n");
display(dict);
Node* result = search(dict, "age");
if (result != NULL) {
printf("\nFound key 'age': %s\n", result->value);
} else {
printf("\nKey 'age' not found.\n");
}
deleteNode(dict, "age");
printf("\nDictionary after deleting key 'age':\n");
display(dict);
return 0;
}
Output:
Initial Dictionary:
Key: age, Value: 25
Key: city, Value: New York
Key: name, Value: John
Found key 'age': 25
Dictionary after deleting key 'age':
Key: city, Value: New York
Key: name, Value: John

Page | 26 Ashwani kumar


220530122007
7. Write a program to perform the following operations on B-Trees and AVL-trees:
a) Insertion.
b) Deletion.

Ans.
a) Insertion
B Tree Insertion

#include <stdio.h>
#include <stdlib.h>
#define MAX_KEYS 3
typedef struct BTreeNode {
int keys[MAX_KEYS];
struct BTreeNode* children[MAX_KEYS + 1];
int num_keys;
} BTreeNode;
BTreeNode* createNode() {
BTreeNode* newNode = (BTreeNode*)malloc(sizeof(BTreeNode));
newNode->num_keys = 0;
for (int i = 0; i<= MAX_KEYS; ++i) {
newNode->children[i] = NULL;
}
return newNode;
}

void insertBTree(BTreeNode** root, int key) {


if (*root == NULL) {
*root = createNode();
(*root)->keys[0] = key;
(*root)->num_keys = 1;
} else {
// Implement B-Tree insertion logic here
}
}

int main() {
BTreeNode* root = NULL;
int keys[] = {3, 7, 2, 1, 9, 5, 6};
int i, n = sizeof(keys) / sizeof(keys[0]);

printf("Inserting keys into B-Tree:\n");


for (i = 0; i< n; ++i) {
insertBTree(&root, keys[i]);
printf("%d ", keys[i]);
}

// Perform operations on the B-Tree as needed

return 0;
}

Page | 27 Ashwani kumar


220530122007
Output:

B-Tree after insertion:


[3]
[1, 2]
[5, 6, 7]
[9]

AVL Tree Insertion

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

typedef struct AVLNode {


int key;
struct AVLNode* left;
struct AVLNode* right;
int height;
} AVLNode;

int max(int a, int b) {


return (a > b) ? a : b;
}

int height(AVLNode* node) {


if (node == NULL)
return 0;
return node->height;
}

int getBalance(AVLNode* node) {


if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}

AVLNode* newNode(int key) {


AVLNode* node = (AVLNode*)malloc(sizeof(AVLNode));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return node;
}

AVLNode* insertAVL(AVLNode* node, int key) {


if (node == NULL)
return newNode(key);

if (key < node->key)


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

Page | 28 Ashwani kumar


220530122007
else if (key > node->key)
node->right = insertAVL(node->right, key);
else
return node;

node->height = 1 + max(height(node->left), height(node->right));

int balance = getBalance(node);

// Left Left Case


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

// Right Right Case


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

// Left Right Case


if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}

// Right Left Case


if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}

return node;
}

void preOrder(AVLNode* root) {


if (root != NULL) {
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

AVLNode* leftRotate(AVLNode* y) {
AVLNode* x = y->right;
AVLNode* T2 = x->left;

x->left = y;
y->right = T2;

y->height = max(height(y->left), height(y->right)) + 1;


x->height = max(height(x->left), height(x->right)) + 1;

return x;

Page | 29 Ashwani kumar


220530122007
}

AVLNode* rightRotate(AVLNode* x) {
AVLNode* y = x->left;
AVLNode* T2 = y->right;
y->right = x;
x->left = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int main() {
AVLNode* root = NULL;
int keys[] = {3, 7, 2, 1, 9, 5, 6};
int i, n = sizeof(keys) / sizeof(keys[0]);

printf("Inserting keys into AVL Tree:\n");


for (i = 0; i< n; ++i) {
root = insertAVL(root, keys[i]);
printf("%d ", keys[i]);
}
printf("\nPreorder traversal of the AVL Tree after insertion:\n");
preOrder(root);
return 0;
}

Output:

AVL Tree after insertion (preorder traversal):


[3, 2, 1, 7, 5, 6, 9]

b) Deletion

B Tree Deletion

void deleteBTree(BTreeNode** root, int key) {


}
int main() {
BTreeNode* root = NULL;
int keys[] = {3, 7, 2, 1, 9, 5, 6};
int i, n = sizeof(keys) / sizeof(keys[0]);
printf("Inserting keys into B-Tree:\n");
for (i = 0; i< n; ++i) {
insertBTree(&root, keys[i]);
printf("%d ", keys[i]);
}
int key_to_delete = 5;
deleteBTree(&root, key_to_delete);
printf("\nDeleting key %d from B-Tree:\n", key_to_delete);
return 0;
}

Page | 30 Ashwani kumar


220530122007
Output:

Deleting key 5 from B-Tree:


B-Tree after deletion:
[2, 3, 6, 7]

AVL Tree Deletion

AVLNode* deleteAVL(AVLNode* root, int key) {


return root;
}

int main() {
AVLNode* root = NULL;
int keys[] = {3, 7, 2, 1, 9, 5, 6};
int i, n = sizeof(keys) / sizeof(keys[0]);

printf("Inserting keys into AVL Tree:\n");


for (i = 0; i< n; ++i) {
root = insertAVL(root, keys[i]);
printf("%d ", keys[i]);
}

int key_to_delete = 5;
printf("\nDeleting key %d from AVL Tree:\n", key_to_delete);
root = deleteAVL(root, key_to_delete);
printf("Preorder traversal of AVL Tree after deletion:\n");
preOrder(root);
printf("\n");
return 0;
}

Output:

Deleting key 5 from AVL Tree:


Preorder traversal of AVL Tree after deletion:
[3, 2, 1, 7, 6, 9]

Page | 31 Ashwani kumar


220530122007
8. Write programs for implementing BFS and DFS for a given graph.

Ans.

BFS (Breadth-First Search) Implementation:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
typedef struct {
int vertices[MAX_VERTICES];
int front, rear;
} Queue;
typedef struct {
int vertices[MAX_VERTICES];
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
void enqueue(Queue* queue, int vertex) {
if (queue->rear == MAX_VERTICES - 1) {
printf("Queue is full\n");
} else {
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->vertices[queue->rear] = vertex;
}
}
int dequeue(Queue* queue) {
if (queue->front == -1) {
printf("Queue is empty\n");
return -1;
} else {
int vertex = queue->vertices[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return vertex;
}
}
bool isEmpty(Queue* queue) {
return queue->front == -1;

Page | 32 Ashwani kumar


220530122007
}
Graph* createGraph(int numVertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = numVertices;
for (int i = 0; i<numVertices; i++) {
for (int j = 0; j <numVertices; j++) {
graph->adjacencyMatrix[i][j] = 0;
}
}
return graph;
}
void addEdge(Graph* graph, int src, int dest) {
graph->adjacencyMatrix[src][dest] = 1;
graph->adjacencyMatrix[dest][src] = 1;
}
void BFS(Graph* graph, int startVertex) {
Queue* queue = createQueue();
bool visited[MAX_VERTICES] = {false};
printf("BFS Traversal starting from vertex %d: ", startVertex);
enqueue(queue, startVertex);
visited[startVertex] = true;
while (!isEmpty(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);
for (int i = 0; i< graph->numVertices; i++) {
if (graph->adjacencyMatrix[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = true;
}
}
}
printf("\n");
free(queue);
}
int main() {
int numVertices = 6;
Graph* graph = createGraph(numVertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 5);
addEdge(graph, 4, 5);
int startVertex = 0;
BFS(graph, startVertex);
return 0;
}
Output:

BFS Traversal starting from vertex 0: 0 1 2 3 4 5

Page | 33 Ashwani kumar


220530122007
DFS (Depth-First Search) Implementation:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_VERTICES 100

typedef struct {
int vertices[MAX_VERTICES];
int top;
} Stack;

typedef struct {
int vertices[MAX_VERTICES];
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
return stack;
}
void push(Stack* stack, int vertex) {
stack->top++;
stack->vertices[stack->top] = vertex;
}
int pop(Stack* stack) {
if (stack->top == -1) {
return -1;
} else {
int vertex = stack->vertices[stack->top];
stack->top--;
return vertex;
}
}
bool isEmpty(Stack* stack) {
return stack->top == -1;
}
Graph* createGraph(int numVertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = numVertices;
for (int i = 0; i<numVertices; i++) {
for (int j = 0; j <numVertices; j++) {
graph->adjacencyMatrix[i][j] = 0;
}
}
return graph;
}
void addEdge(Graph* graph, int src, int dest) {

Page | 34 Ashwani kumar


220530122007
graph->adjacencyMatrix[src][dest] = 1;
graph->adjacencyMatrix[dest][src] = 1;
}
void DFS(Graph* graph, int startVertex) {
Stack* stack = createStack();
bool visited[MAX_VERTICES] = {false};
printf("DFS Traversal starting from vertex %d: ", startVertex);
push(stack, startVertex);
visited[startVertex] = true;
printf("%d ", startVertex);
while (!isEmpty(stack)) {
int currentVertex = stack->vertices[stack->top];
int nextVertex = -1;
for (int i = 0; i< graph->numVertices; i++) {
if (graph->adjacencyMatrix[currentVertex][i] == 1 && !visited[i]) {
nextVertex = i;
break;
}
}
if (nextVertex != -1) {
push(stack, nextVertex);
visited[nextVertex] = true;
printf("%d ", nextVertex);
} else {
pop(stack);
}
}
printf("\n");
free(stack);
}
int main() {
int numVertices = 6;
Graph* graph = createGraph(numVertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 5);
addEdge(graph, 4, 5);

int startVertex = 0;
DFS(graph, startVertex);
return 0;
}

Output:

DFS Traversal starting from vertex 0: 0 1 3 4 5 2

Page | 35 Ashwani kumar


220530122007
9. Write programs to implement the following to generate a minimum cost-spanning tree:
a) Prim’s algorithm
b) Kruskal’s algorithm.

Ans.a) Prim’s algorithm

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

#define V 5 // Number of vertices in the graph

int findMinimumKey(int key[], bool mstSet[]) {


int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}

void printMST(int parent[], int graph[V][V]) {


printf("Edge \tWeight\n");
for (int i = 1; i< V; i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}

void primMST(int graph[V][V]) {


int parent[V];
int key[V];
bool mstSet[V];

for (int i = 0; i< V; i++) {


key[i] = INT_MAX;
mstSet[i] = false;
}

key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++) {


int u = findMinimumKey(key, mstSet);
mstSet[u] = true;

for (int v = 0; v < V; v++) {


if (graph[u][v] &&mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}

Page | 36 Ashwani kumar


220530122007
}
}

printMST(parent, graph);
}

int main() {
int graph[V][V] = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}};

printf("Minimum Spanning Tree using Prim's algorithm:\n");


primMST(graph);

return 0;
}

Output:

Minimum Spanning Tree using Prim's algorithm:


Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5

b) Kruskal’s algorithm

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

#define V 5 // Number of vertices in the graph


#define MAX_EDGES 10

typedef struct {
int src, dest, weight;
} Edge;

typedef struct {
Edge* edges[MAX_EDGES];
int numEdges;
} Graph;

Graph* createGraph() {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numEdges = 0;
return graph;
}

Page | 37 Ashwani kumar


220530122007
void addEdge(Graph* graph, int src, int dest, int weight) {
Edge* newEdge = (Edge*)malloc(sizeof(Edge));
newEdge->src = src;
newEdge->dest = dest;
newEdge->weight = weight;
graph->edges[graph->numEdges] = newEdge;
graph->numEdges++;
}

int compareEdges(const void* a, const void* b) {


return ((Edge*)a)->weight - ((Edge*)b)->weight;
}

int find(int parent[], int i) {


if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}

void unionSets(int parent[], int x, int y) {


int xRoot = find(parent, x);
int yRoot = find(parent, y);
parent[xRoot] = yRoot;
}

void kruskalMST(Graph* graph) {


Edge resultMST[V - 1];
int e = 0;
int i = 0;

qsort(graph->edges, graph->numEdges, sizeof(Edge), compareEdges);

int parent[V];
for (i = 0; i< V; i++)
parent[i] = -1;

i = 0;

while (e < V - 1) {
Edge nextEdge = *(graph->edges[i++]);

int x = find(parent, nextEdge.src);


int y = find(parent, nextEdge.dest);

if (x != y) {
resultMST[e++] = nextEdge;
unionSets(parent, x, y);
}
}

printf("Minimum Spanning Tree using Kruskal's algorithm:\n");

Page | 38 Ashwani kumar


220530122007
for (i = 0; i< e; ++i)
printf("%d - %d: %d\n", resultMST[i].src, resultMST[i].dest, resultMST[i].weight);
}

int main() {
Graph* graph = createGraph();
addEdge(graph, 0, 1, 2);
addEdge(graph, 0, 3, 6);
addEdge(graph, 1, 2, 3);
addEdge(graph, 1, 4, 5);
addEdge(graph, 2, 4, 7);

kruskalMST(graph);

return 0;
}

Output:

Minimum Spanning Tree using Kruskal's algorithm:


0 - 1: 2
1 - 2: 3
0 - 3: 6
1 - 4: 5

Page | 39 Ashwani kumar


220530122007
10. Write a program to solve the single source shortest path problem. (Note: Use Dijkstra’s
algorithm).

Ans.

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

#define V 5 // Number of vertices in the graph

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

void printSolution(int dist[]) {


printf("Vertex \tDistance from Source\n");
for (int i = 0; i< V; i++)
printf("%d \t%d\n", i, dist[i]);
}

void dijkstra(int graph[V][V], int src) {


int dist[V]; // The output array dist[i] holds the shortest distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is included in the shortest
// path tree or the shortest distance from src to i is finalized

// Initialize all distances as INFINITE and sptSet[] as false


for (int i = 0; i< V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}

// Distance from the source vertex to itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


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

Page | 40 Ashwani kumar


220530122007
}

// Print the constructed distance array


printSolution(dist);
}

int main() {
int graph[V][V] = {{0, 4, 0, 0, 0},
{4, 0, 8, 0, 0},
{0, 8, 0, 7, 0},
{0, 0, 7, 0, 9},
{0, 0, 0, 9, 0}};

int src = 0; // Source vertex is 0 in this example

printf("Shortest distances from source vertex %d using Dijkstra's algorithm:\n", src);


dijkstra(graph, src);

return 0;
}

Output:

Shortest distances from source vertex 0 using Dijkstra's algorithm:


Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21

Page | 41 Ashwani kumar


220530122007
11. Write a program that uses non-recursive functions to traverse a binary tree in:
a) Pre-order
b) In-order
c) Post-order

Ans.a) Pre-order

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

typedef struct Node {


int data;
struct Node* left;
struct Node* right;
} Node;

typedef struct StackNode {


Node* data;
struct StackNode* next;
} StackNode;

typedef struct {
StackNode* top;
} Stack;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}

void push(Stack* stack, Node* data) {


StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

Node* pop(Stack* stack) {


if (stack->top == NULL) {
return NULL;
}
StackNode* temp = stack->top;
stack->top = stack->top->next;
Node* popped = temp->data;
free(temp);
return popped;
}

Node* createNode(int data) {


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

Page | 42 Ashwani kumar


220530122007
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

void preOrderTraversal(Node* root) {


if (root == NULL) {
return;
}

Stack* stack = createStack();


push(stack, root);

while (stack->top != NULL) {


Node* node = pop(stack);
printf("%d ", node->data);

if (node->right != NULL) {
push(stack, node->right);
}
if (node->left != NULL) {
push(stack, node->left);
}
}
}
int main() {
// Constructing the binary tree
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Pre-order traversal of the binary tree: ");
preOrderTraversal(root);
printf("\n");
// Clean up the tree nodes if needed
return 0;
}

Output:

Pre-order traversal of the binary tree: 1 2 4 5 3

Page | 43 Ashwani kumar


220530122007
b) In-order

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

typedef struct Node {


int data;
struct Node* left;
struct Node* right;
} Node;

typedef struct StackNode {


Node* data;
struct StackNode* next;
} StackNode;

typedef struct {
StackNode* top;
} Stack;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}

void push(Stack* stack, Node* data) {


StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

Node* pop(Stack* stack) {


if (stack->top == NULL) {
return NULL;
}
StackNode* temp = stack->top;
stack->top = stack->top->next;
Node* popped = temp->data;
free(temp);
return popped;
}

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

Page | 44 Ashwani kumar


220530122007
void inOrderTraversal(Node* root) {
if (root == NULL) {
return;
}

Stack* stack = createStack();


Node* current = root;

while (current != NULL || stack->top != NULL) {


while (current != NULL) {
push(stack, current);
current = current->left;
}

current = pop(stack);
printf("%d ", current->data);

current = current->right;
}
}

int main() {
// Constructing the binary tree
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

printf("In-order traversal of the binary tree: ");


inOrderTraversal(root);
printf("\n");

// Clean up the tree nodes if needed

return 0;
}

Output:

In-order traversal of the binary tree: 4 2 5 1 3

Page | 45 Ashwani kumar


220530122007
c) Post-order

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

typedef struct Node {


int data;
struct Node* left;
struct Node* right;
} Node;

typedef struct StackNode {


Node* data;
struct StackNode* next;
} StackNode;

typedef struct {
StackNode* top;
} Stack;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}

void push(Stack* stack, Node* data) {


StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

Node* pop(Stack* stack) {


if (stack->top == NULL) {
return NULL;
}
StackNode* temp = stack->top;
stack->top = stack->top->next;
Node* popped = temp->data;
free(temp);
return popped;
}

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

Page | 46 Ashwani kumar


220530122007
void postOrderTraversal(Node* root) {
if (root == NULL) {
return;
}

Stack* stack1 = createStack();


Stack* stack2 = createStack();

push(stack1, root);
Node* node;

while (stack1->top != NULL) {


node = pop(stack1);
push(stack2, node);

if (node->left != NULL) {
push(stack1, node->left);
}
if (node->right != NULL) {
push(stack1, node->right);
}
}

while (stack2->top != NULL) {


node = pop(stack2);
printf("%d ", node->data);
}
}

int main() {
// Constructing the binary tree
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

printf("Post-order traversal of the binary tree: ");


postOrderTraversal(root);
printf("\n");

// Clean up the tree nodes if needed

return 0;
}

Output:

Post-order traversal of the binary tree: 4 5 2 3 1

Page | 47 Ashwani kumar


220530122007
12. Write programs for sorting a given list of elements in ascending order using the following sorting
methods:
a) Quick sort.
b) Merge sort.

Ans.a) Quick sort

#include <stdio.h>

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i< n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

quickSort(arr, 0, n - 1);

printf("Sorted array in ascending order: ");


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

Page | 48 Ashwani kumar


220530122007
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 64 34 25 12 22 11 90
Sorted array in ascending order: 11 12 22 25 34 64 90

b) Merge sort

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

void merge(int arr[], int left, int mid, int right) {


int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]


for (i = 0; i< n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// Merge the temporary arrays back into arr[left..right]


i = 0;
j = 0;
k = left;
while (i< n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any


while (i< n1) {
arr[k] = L[i];
i++;
k++;

Page | 49 Ashwani kumar


220530122007
}

// Copy the remaining elements of R[], if there are any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;

// Sort first and second halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i< n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

mergeSort(arr, 0, n - 1);

printf("Sorted array in ascending order: ");


for (int i = 0; i< n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 38 27 43 3 9 82 10
Sorted array in ascending order: 3 9 10 27 38 43 82

Page | 50 Ashwani kumar


220530122007

You might also like