School of IT
Institute of Management Studies - Noida
MCA (2021-2023)
Practical File
Data Structures & Analysis of Algorithms
(KCA-253)
Submitted To: Submitted By:
Mrs. Jyoti K Tripathi Sudhanshu Vishwakarma
Assistant Professor SOIT Roll No.:- 2100980140044
Practical List OF Data structure Analysis And Algorithm (KCA-253)
Faculty Name: Jyoti K Tripathi
Sr. Name Of The Program Page No. Date Sig
No. n
1 Write a program to implement linked
list
and also print all the elements of the
same
2 . Write a program to implement the
stack
using array data structure
3 Write a program to implement queue
using
array.
4 Write a program to perform in
Enqueue(insertion) in a queue
using array
data structure.
5 Write a program to perform binary
search
on a given list.
6 Write a program for insertion and
deletion
of element in binary search tree.
Write a C program to
7 implement to insertion sort on
8 a list to arrange it ascending
order
9 Write a C program to implement
selection sort on a list to arrange it in
descending order .
10 Write a C program to implement
Bubble sort on a list to arrange it in
ascending order .
11 Write a C program to implement
Heap Sort.
12 Write a C program to implement Quick
Sort
13 Write a program to implement BFS &
DFS.
14 Write a program to implement
linear search.
15 Write a program to implement stack
as an array.
16 Write a program to implement binary
tree traversal.
17 Write a program to implement
quick sort.
18 Write a program to implement
Dijkstra algorithm
19 Write a program to implement
merge
sort.
20 Write a Program to implement
Prim’s
Algorithm
21 Write a Program to implement
Kruskal’s Algorithm
22 Write a Program to implement AVL
Tree
23 Write a program to implement
single linked list (insertion-begin,
end, middle).
24 Write a program to calculate
factorial of any number using
recursion.
25 Write a program to print Fibonacci
series using recursion
.
Q 1: Write a program to implement linked list and also print all the elements of the
same
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *nextptr;
}*stnode;
void createNodeList(int n);
void displayList();
int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL;
tmp = stnode;
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num;
fnNode->nextptr = NULL;
tmp->nextptr = fnNode; tmp = tmp->nextptr;
}
}
}
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num);
tmp = tmp->nextptr;
}
}
OUTPUT 1:
Q 2: Write a program to implement the stack using
arrray data structure.
#include<stdio.h>
void push(char element, char stack[], int *top, int
stackSize){
if(*top == -1){
stack[stackSize - 1] = element;
*top = stackSize - 1;
}
else if(*top == 0){
printf("The stack is already full. \n");
}
else{
stack[(*top) - 1] = element;
(*top)--;
}}
void pop(char stack[], int *top, int stackSize){
if(*top == -1){
printf("The stack is empty. \n");
}
else{
printf("Element popped: %c \n", stack[(*top)]);
// If the element popped was the last element in the stack
// then set top to -1 to show that the stack is empty
if((*top) == stackSize - 1){
(*top) = -1;
}
else{
(*top)++;
} }}
int main() {
int stackSize = 4;
char stack[stackSize];
// A negative index shows that the stack is empty
int top = -1;
push('a', stack, &top, stackSize);
printf("Element on top: %c\n", stack[top]);
push('b',stack, &top, stackSize);
printf("Element on top: %c\n", stack[top]);
pop(stack, &top, stackSize);
printf("Element on top: %c\n", stack[top]);
pop(stack, &top, stackSize);
printf("Top: %d\n", top);
pop(stack, &top, stackSize);
return 0;}
OUTPUT 2:
Q 3: Write a program to implement queue using
array.
#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;
case 4:
exit(0);
default:
printf("Wrong Choice: please see
the options"); } } }
return 0;}
OUTPUT 3:
Q 4:Write a program to perform in insertion in a queue using
array data structure
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 6
int intArray[MAX];
int front = 0;
int rear = -1;
int itemCount = 0;
int peek ()
{ return intArray[front];
bool isEmpty ()
{ return itemCount == 0;
bool isFull ()
{ return itemCount == MAX;
int size ()
{ return itemCount;
void enqueue(int data)
{ if (!isFull ())
{ if (rear == MAX - 1)
{ rear = -1;
}
intArray[++rear] = data;
itemCount++;
}}
int dequeue()
int data = intArray[front++];
if (front == MAX)
front = 0; }
itemCount--;
return data;
int main ()
enqueue (3);
enqueue (5);
enqueue (9);
enqueue (1);
enqueue (12);
enqueue (15);
if (isFull ())
printf ("Queue is full!\n");
int num = dequeue ();
printf ("Element removed: %d\n", num);
enqueue (16);
enqueue (17);
enqueue (18);
printf ("Element at front: %d\n", peek ());
printf ("----------------------\n");
printf ("index : 5 4 3 2 1 0\n");
printf ("----------------------\n");
printf ("Queue: ");
while (!isEmpty ())
int n = dequeue();
printf ("%d ", n);
Output 4:
Q 5: Write a program to perform binary search on a given list.
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
if(a[mid] == val) {
return mid+1;
}
else if(a[mid] < val) {
return binarySearch(a, mid+1, end, val);
}
else {
return binarySearch(a, beg, mid-1, val);
} }
return -1; }
int main() {
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70}; // given array
int val = 40; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = binarySearch(a, 0, n-1, val); // Store result
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}
OUTPUT 5:
Q 6: Write a program for insertion and
deletion of element in binary search tree
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;};
struct Node* createNode(int data) {
struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
} return root;
}struct Node* minValueNode(struct Node* node) {
struct Node* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;}
struct Node* deleteNode(struct Node* root, int data) {
if (root == NULL) {
return root; }
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
} struct Node* temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
} return root;}
void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right); }
}int main() {
struct Node* root = NULL;
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 70);
root = insert(root, 60);
printf("Inorder traversal before deletion: ");
inorderTraversal(root);
printf("\n");
root = deleteNode(root, 20);
root = deleteNode(root, 30);
root = deleteNode(root, 70);
printf("Inorder traversal after deletion: ");
inorderTraversal(root);
printf("\n");
return 0;
OUTPUT 6:
Q 7,8: Write a program to implement Insertion sort
arrange it in ascending order.
#include <stdio.h>
int main(){
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 - 1; 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 - 1; i++){
printf("%d\n", arr[i]);}
return 0;}Output 7 :-
Q 9: Write a program to implement selection sort on a list to arrange it in decending order.
#include <stdio.h>
int main()
{
int arr[] = {5, 2, 8, 7, 1};
int temp = 0;
int length = sizeof(arr)/sizeof(arr[0]);
printf("Elements of original array: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
for (int i = 0; i < length; i++) {
for (int j = i+1; j < length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp; } } }
printf("\n");
printf("Elements of array sorted in descending order: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]); }
return 0; }
OUTPUT 9:-
Q 10: Write a program to implement bubble sort on a list to arrange it in ascending order.
#include <stdio.h>
void bubblesort(int arr[], int size)
int i, j;
for (i = 0; i < size; i++)
for (j = 0; j < size - i; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);}}}
void swap(int *a, int *b)
{int temp; temp = *a;
*a = *b;
*b = temp;}
int main()
int array[100], i, size;
printf("How many numbers you want to sort:
"); scanf("%d", &size);
printf("\nEnter %d numbers : ",
size); for (i = 0; i < size; i++)
scanf("%d", &array[i]);
bubblesort(array, size);
printf("\nSorted array is ");
for (i = 0; i < size; i++)
printf(" %d ", array[i]);
return 0;
OUTPUT 10:-
Q 11:Write a C program to implement Heap Sort.
#include<stdio.h>
void heapsort(int[],int);
void heapify(int[],int);
void adjust(int[],int);
main() {
int n,i,a[50];
system("clear");
printf("\nEnter the limit:");
scanf("%d",&n);
printf("\nEnter the elements:");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("\nThe Sorted Elements Are:\n");
for (i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");}
void heapsort(int a[],int n) {
int i,t;
heapify(a,n);
for (i=n-1;i>0;i--) {
t = a[0];
a[0] = a[i];
a[i] = t;
adjust(a,i);}}
void heapify(int a[],int n) {
int k,i,j,item;
for (k=1;k<n;k++) {
item = a[k];
i = k;
j = (i-1)/2;
while((i>0)&&(item>a[j])) {
a[i] = a[j];
i = j;
j = (i-1)/2;}
a[i] = item;}}
void adjust(int a[],int n) {
int i,j,item;
j = 0;
item = a[j];
i = 2*j+1;
while(i<=n-1) {
if(i+1 <= n-1)
if(a[i] <a[i+1])
i++;
if(item<a[i]) {
a[j] = a[i];
j = i;
i = 2*j+1;
} else
break;}
a[j] = item;}
OUTPUT 11:
Q 12: Write a program to implement quick sort.
#include <stdio.h>
void quicksort (int [], int,
int); int main(){
int list[50]; int size, i;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\
n"); for (i = 0; i < size; i++){
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1); printf("After applying quick sort\n"); for (i = 0; i < size; i++){printf("%d ",
list[i]);}printf("\n"); return 0;
}
void quicksort(int list[], int low, int high)
{int pivot, i, j, temp; if (low < high)
pivot =low;
i = low;
j = high;
while (i<j)
while(list=
list[pivot]
&& i <=
high)
{ i+
+;}while
(list[j] >
list[pivot]
&& j >low)
{j--;}
if (i < j)
{
temp=
list[i]; list[i]
= list[j];
list[j]=
temp;}}
temp=
list[j];
list[j]=list[pi
vot];
list[pivot] =
temp;
quicksort(lis
t, low, j - 1);
quicksort(lis
t, j+
1high);}
Output 12:
Q 13: Write a program to implement BFS & DFS.
#include<stdio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();
void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}
//**************BFS(breadth-first search) code**************//
void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}
void add(int item)
{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}
void dfs(int s,int n){
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0)){
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item){
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop(){
int k;
if(top==-1)
return(0);
else{
k=stack[top--];
return(k);
}}
OUTPUT 13:
Q 14 :- Write a program to implement linear search.
#include <stdio.h>
void main()
{int num;
int i, keynum, found = 0;
printf("Enter the number of elements ");
scanf("%d", &num);
int array[num];
printf("Enter the elements one by one \
n"); for (i = 0; i < num; i++){
scanf("%d", &array[i]);}
printf("Enter the element to be searched ");
scanf("%d", &keynum);
for (i = 0; i < num ; i++){
if (keynum == array[i] ){
found = 1; break;}}
if (found == 1)
printf("Element is present in the array at position
%d",i+1); else
printf("Element is not present in the array\n");}
OUTPUT 14:-
Q 15: Write a program to implement stack as an array
#include<limits.h
>#include<stdio.h
>#include<stdlib.
h> struct Stack {
int top;
unsigned
capacity;
int* array;
};struct Stack* createStack(unsigned capacity){
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity *
sizeof(int)); return stack;
}int isFull(struct Stack* stack)
{return stack->top == stack->capacity - 1;}
int isEmpty(struct Stack* stack){
return stack->top == -1;
}void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}int pop(struct Stack* stack)
{if (isEmpty(stack)) return INT_MIN;
return stack->array[stack->top--];
}int peek(struct Stack* stack)
{if (isEmpty(stack)) return INT_MIN;
return stack->array[stack->top];
}int main()
{struct Stack* stack = createStack(100); push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
return 0;
Output 15:
Q 16: Write a program to implement binary tree traversal.
#include <stdio.h>
#include <stdlib.h>
struct tnode {
int data;
struct tnode *left, *right;
};
struct tnode *root = NULL;
/* creating node of the tree and fill the given data */
struct tnode * createNode(int data) {
struct tnode *newNode;
newNode = (struct tnode *) malloc(sizeof(struct tnode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return (newNode);
}
/* inserting a new node into the tree */
void insertion(struct tnode **node, int data) {
if (!*node) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
} }
void postOrder(struct tnode *node) {
if (node) {
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
return;
} void preOrder(struct tnode *node) {
if (node) {
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
return;
} void inOrder(struct tnode *node) {
if (node) {
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right); }
return;
}
int main() {
int data, ch;
while (1) {
printf("\n1. Insertion\n2. Pre-order\n");
printf("3. Post-order\n4. In-order\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter ur data:");
scanf("%d", &data);
insertion(&root, data);
break;
case 2:
preOrder(root);
break;
case 3:
postOrder(root);
break;
case 4:
inOrder(root);
break;
case 5:
exit(0);
default:
printf("U've entered wrong opetion\n");
break;
}}
return 0;
}
Output 16:
Q 17: Write a program to implement quick sort
#include <stdio.h>
int partition (int a[], int start, int end) {
int pivot = a[end int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{ if (a[j] < pivot) {
i++;
int t = a[i];
a[i] = a[j];
a[j] = t; } }
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
} void quick(int a[], int start, int end) {
if (start < end) {
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end); } }
void printArr(int a[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
} int main() {
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0; }
OUTPUT 17:
Q 18: Write a program to implement Dijkstra algorithm.
#include<stdio.h>
#include<conio.h>
#define INFINITY
9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode); int main()
{
int G[MAX][MAX],i,j,n,u;
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]); printf("\
nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u)
; return 0;}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX]
[MAX],distance[MAX],pred[MAX]; int
visited[MAX],count,mindistance,nextnode,i,j;
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];
for(i=0;i<n;i++)
{
distance[i]=cost[startnode]
[i]; pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=
0;
visited[startnode]=1
; count=0;
while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i]) if(mindistance+cost[nextnode]
[i]<distance[i])
{
distance[i]=mindistance+cost[nextnode
][i]; pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++) if(i!
=startnode)
{
printf("\nDistance of node %d=%d",i,distance[i]); printf("\
nPath=%d",i);
j=i
;
do
{
j=pred[j];
printf("<-
%d",j);
}while(j!=startnode);
}
}
Output 18:-
Q 19: Write a program to implement merge sort.
#include <stdio.h>
void mergeSort(int [], int, int,
int); void partition(int [],int, int);
int main() {
int list[50]; int i, size;
printf("Enter total number of elements:”);
scanf("%d", &size);
printf("Enter the elements:\n"); for(i = 0; i <
size; i++){
scanf("%d", &list[i]);}
partition(list, 0, size - 1); printf("After merge
sort:\n"); for(i = 0;i < size; i++){
printf("%d ",list[i]);
}return 0;
}void partition(int list[],int low,int high)
{
int mid; if(low < high)
{
mid = (low + high) / 2; partition(list, low, mid); partition(list, mid + 1, high); mergeSort(list, low, mid,
high);}}
void mergeSort(int list[],int
low,int mid,int high){
int i, mi, k, lo,
temp[50]; lo = low;
i = low;
mi = mid + 1;
while ((lo <= mid) && (mi <= high)){
if (list[lo] <= list[mi]){
temp[i] =
list[lo]; lo++;
}else
{temp[i] = list[mi]; mi++;}
i++;}if (lo > mid){
for (k = mi; k <= high; k++){
temp[i] =
list[k]; i++;
}}
else
for (k = lo; k <= mid; k++){
temp[i] =
list[k]; i++;
}}
for (k = low; k <= high; k++)
{
list[k] = temp[k];
}}
Output 19:-
Q 20: Write a Program to implement Prim’s Algorithm.
#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;
}
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0;
no_of_edges=n-1;
while(no_of_edges>
0)
{
min_distance=infinit
y; for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i]
}
u=from[v]; spanning[u]
[v]=distance[v];
spanning[v]
[u]=distance[v];
no_of_edges--;
visited[v]=1;
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);
}
Output 20:-
Q 21: Write a Program to implement Kruskal’s Algorithm.
#include<stdio.h>
#define MAX 30
typedef struct edge
{
int u,v,w;
}edge;
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();
void main()
{
int i,j,total_cost;
printf("\nEnter number 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]);
kruskal();
print();
}
void kruskal(){
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
for(i=1;i<n;i++)
for(j=0;j<i;j++)
{ if(G[i][j]!
=0{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j]; elist.n++;
}}
sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}}}
int find(int belongs[],int vertexno){
return(belongs[vertexno]);
}
void union1(int belongs[],int c1,int c2){
int i; for(i=0;i<n;i+
+)
if(belongs[i]==c2)
belongs[i]=c1;
}void sort()
{
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}}
void print(){
int i,cost=0;
for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}
printf("\n\nCost of the spanning tree=%d",cost);
}
OUTPUT 21:
Q.22. Write a program to implement a AVL tree.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};
int height(struct Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
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;
node->right = NULL;
node->height = 1;
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 = max(height(y->left),
height(y->right)) + 1;
x->height = max(height(x->left),
height(x->right)) + 1;
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 = max(height(x->left),
height(x->right)) + 1;
y->height = max(height(y->left),
height(y->right)) + 1;
return y;
}
int getBalance(struct Node *N)
{
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 = 1 + max(height(node->left),
height(node->right));
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);
}
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");
preOrder(root);
return 0;
}
Output 22:
Q 23: Write a program to implement single linked list (insertion-begin, end,
middle).
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
} struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
} current->next = newNode;
}
void insertAtMiddle(struct Node** head, int data, int position) {
if (*head == NULL || position == 0) {
insertAtBeginning(head, data);
return;
}struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
struct Node* current = *head;
int count = 0;
while (count < position - 1 && current->next != NULL) {
current = current->next;
count++;
}
newNode->next = current->next;
current->next = newNode;
}
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}printf("\n");
}
int main() {
struct Node* head = NULL;
insertAtBeginning(&head, 3);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 1);
printf("List after inserting at the beginning: ");
printList(head);
insertAtEnd(&head, 4);
insertAtEnd(&head, 5);
printf("List after inserting at the end: ");
printList(head);
insertAtMiddle(&head, 10, 2);
insertAtMiddle(&head, 7, 4);
printf("List after inserting at the middle: ");
printList(head);
return 0;
}
OUTPUT 23:
Q 24: Write a program to calculate factorial of any number using recursion.
#include<stdio.h>
long int multiplyNumbers(int
n); int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
long int multiplyNumbers(int n)
if (n>=1)
return n*multiplyNumbers(n-
1); else
return 1;
Output 24 :-
Q 25: Write a program to print Fibonacci series using recursion.
#include<stdio.h>
int main()
int n1=0,n2=1,n3,i,number;
printf("Enter the number of
elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
n3=n1+n2;
printf("
%d",n3);
n1=n2;
n2=n3;
return 0;
Output 25 :-