AVL Tree Operations in C Programming
AVL Tree Operations in C Programming
Page No: 1
[Link]: 1
Deletion and Search Operations 17
Aim:
ID: 24BQ1A05U9
Write a C program to implement an AVL Tree (self-balancing Binary Search Tree) with the
following functionalities:
• Insert(): Insert a node into the AVL Tree.
• Delete(): Delete a node from the AVL Tree.
• Search(): Search for a node in the AVL Tree.
• Inorder(): Perform an inorder traversal of the AVL Tree, displaying balance factors.
• Exit(): Terminate the program.
Menu Options:
[Link] [Link] [Link] [Link] Traversal [Link]
Option 1: Insert
2024-2028-CSE-E
• Prompt the user with:
Enter an element to be inserted : <value>
• Insert the value into the AVL Tree.
• If the element is already present, display:
Element <value> already exists.
• On successful insertion, print:
Successfully inserted.
Option 3: Search
• Prompt the user with:
Enter an element to be searched : <value>
• If the value exists in the tree:
Element found in the AVL Tree.
• If not found:
Element not found in the AVL Tree.
Page No: 2
where <val> is the node value and <bf> is the node's balance factor.
Option 5: Exit
• Exit the program.
ID: 24BQ1A05U9
Note:
• The required print statements are already provided in the code. You need to
implement the remaining functionality accordingly.
• Ensure rotations (LL, RR, LR, RL) are applied to maintain AVL balance after
insertions and deletions.
• Follow the output format strictly to match visible test cases.
Source Code:
AVLTreeMain1.c
2024-2028-CSE-E
Vasireddy Venkatadri Institute of Technology
#include<stdio.h>
Page No: 3
#include<stdlib.h>
#include<conio.h>
#include "AVLTreeOperations.c"
int main() {
ID: 24BQ1A05U9
int x, op;
AVLNODE root = NULL;
while(1) {
printf("[Link] [Link] [Link] [Link] Traversal
[Link]\n");
printf("Enter your option : ");
scanf("%d", &op);
switch(op) {
case 1: printf("Enter an element to be inserted
: ");
scanf("%d", &x);
2024-2028-CSE-E
root = insertNodeInAVL(root,x);
break;
case 2: printf("Enter an element to be deleted
: ");
scanf("%d", &x);
root = deleteNodeInAVL(root,x);
break;
AVLTreeOperations.c
case 5: exit(0);
}
break;
Page No: 5
int data;
struct node *left,*right;
int ht;
};
typedef struct node * AVLNODE;
ID: 24BQ1A05U9
AVLNODE createNodeInAVL(int item) {
AVLNODE temp = (AVLNODE)malloc(sizeof(struct node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
int height(AVLNODE root) {
int lh,rh;
if(root==NULL)
return(0);
if(root->left==NULL)
2024-2028-CSE-E
lh=0;
else
lh=1+root->left->ht;
if(root->right==NULL)
rh=0;
else
rh=1+root->right->ht;
AVLNODE rotateRight(AVLNODE x) {
AVLNODE y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
AVLNODE rotateLeft(AVLNODE x) {
AVLNODE y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
Page No: 6
}
AVLNODE LL(AVLNODE root) {
root=rotateLeft(root);
return(root);
}
ID: 24BQ1A05U9
AVLNODE RR(AVLNODE root) {
root=rotateRight(root);
return(root);
}
AVLNODE LR(AVLNODE root) {
root->left=rotateLeft(root->left);
root=rotateRight(root);
return(root);
}
AVLNODE RL(AVLNODE root) {
root->right=rotateRight(root->right);
2024-2028-CSE-E
root=rotateLeft(root);
return(root);
}
int balancefactor(AVLNODE root) {
int lh,rh;
if(root==NULL)
return(0);
Page No: 7
}
else if(x>root->data){
root->right = insertNodeInAVL(root->right,x);
if(balancefactor(root)==-2){
if(x>root->right->data)
ID: 24BQ1A05U9
root=LL(root);
else
root=LR(root);
}
}
else if(x<root->data){
root->left=insertNodeInAVL(root->left,x);
if(balancefactor(root)==2){
if(x<root->left->data)
root=RR(root);
else
2024-2028-CSE-E
root=LR(root);
}
}
else{
printf("Element %d already exists.\n",x);
}
root->ht=height(root);
Page No: 8
if(balancefactor(root->right)<=0)
root=RR(root);
else
root=RL(root);
}
ID: 24BQ1A05U9
}
else{
if(root->right!=NULL){
temp = root->right;
while(temp->left!=NULL){
temp=temp->left;
}
root->data=temp->data;
temp->data=x;
root->right=deleteNodeInAVL(root-
>right,temp->data);
2024-2028-CSE-E
if(balancefactor(root)==2){
if(balancefactor(root-
>left)>=0)
root=LL(root);
else
root=LR(root);
}
Page No: 9
User Output
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
ID: 24BQ1A05U9
1
Enter an element to be inserted :
42
Successfully inserted.
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
1
Enter an element to be inserted :
23
Successfully inserted.
2024-2028-CSE-E
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
1
Enter an element to be inserted :
45
Successfully inserted.
Page No: 10
3
Enter an element to be searched :
45
Element found in the AVL tree.
ID: 24BQ1A05U9
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
1
Enter an element to be inserted :
42
Successfully inserted.
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
4
2024-2028-CSE-E
Elements of the AVL tree (In-order traversal): 23(0) 42(0) 45(0)
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
5
Test Case - 2
Page No: 11
19
Successfully inserted.
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
ID: 24BQ1A05U9
1
Enter an element to be inserted :
17
Successfully inserted.
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
1
Enter an element to be inserted :
19
2024-2028-CSE-E
Element 19 already exists.
[Link] [Link] [Link] [Link] Traversal [Link]
Enter your option :
1
Enter an element to be inserted :
18
Page No: 13
01
Aim:
Write a C program that creates a min heap of integers, display the values and perform
ID: 24BQ1A05U9
deletion operation.
Input Format:
• An integer n – the number of elements to be inserted into the Min Heap.
• n integers separated by space – the elements to be inserted into the Min Heap.
Output Format:
• Print the string "Min Heap:" followed by the elements of the Min Heap after all
insertions in a single line separated by spaces.
• Print the string "Extracting elements from the min heap:" followed by lines for each
extracted element until the heap is empty.
2024-2028-CSE-E
• Each extraction should print: "Extracted: x", where x is the smallest element
extracted from the Min Heap in order, each on a new line.
Source Code:
minHeapOfIntegers.c
Page No: 14
#define MAX_HEAP_SIZE 100
ID: 24BQ1A05U9
int temp = *x;
*x = *y;
*y = temp;
}
2024-2028-CSE-E
smallest = left;
if(right< n && arr[right] <arr[smallest])
smallest = right;
if(smallest!=i){
swap(&arr[i],&arr[smallest]);
minHeapify(arr,n,smallest);
}
Page No: 15
int root = arr[0];
arr[0] = arr[*n-1];
(*n)--;
minHeapify(arr,*n,0);
return root;
ID: 24BQ1A05U9
}
int main() {
int arr[MAX_HEAP_SIZE];
int n;
2024-2028-CSE-E
scanf("%d", &arr[i]);
buildMinHeap(arr, n);
displayHeap(arr, n);
return 0;
}
User Output
Enter no of elements:
5
Enter elements:
12648
Min Heap: 1 2 6 4 8
Extracting elements from the min heap:
Page No: 16
Extracted: 1
Extracted: 2
Extracted: 4
Extracted: 6
ID: 24BQ1A05U9
Extracted: 8
Test Case - 2
User Output
Enter no of elements:
6
Enter elements:
251684
2024-2028-CSE-E
Min Heap: 1 5 2 6 8 4
Extracting elements from the min heap:
Extracted: 1
Extracted: 2
Extracted: 4
Extracted: 5
Page No: 17
01
Aim:
Write a C program that creates a max heap of integers, display the values and perform
ID: 24BQ1A05U9
deletion operations.
Input Format:
• An integer n — the number of elements to insert into the Max Heap.
• n integers separated by spaces — the elements to insert into the Max Heap.
Output Format:
• Print "Max Heap:" followed by the elements of the Max Heap after all insertions
which are space seperated.
• Print "Extracting elements from max heap:"
• Next n Lines, for each extraction, print a line "Extracted: x" where x is the element
2024-2028-CSE-E
extracted one per line, until the heap is empty. The extracted elements will be in
descending order.
Source Code:
maxHeapOfIntegers.c
Page No: 18
#define MAX_HEAP_SIZE 100
ID: 24BQ1A05U9
int temp = *x;
*x = *y;
*y = temp;
}
2024-2028-CSE-E
largest = left;
if(right<n && arr[right]>arr[largest])
largest = right;
if(largest!=i){
swap(&arr[i],&arr[largest]);
maxHeapify(arr,n,largest);
}
Page No: 19
int root = arr[0];
arr[0]=arr[*n-1];
(*n)--;
maxHeapify(arr,*n,0);
return root;
ID: 24BQ1A05U9
}
int main() {
int arr[MAX_HEAP_SIZE];
int n;
printf("elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
2024-2028-CSE-E
buildMaxHeap(arr, n);
displayHeap(arr, n);
return 0;
}
User Output
Enter no of elements:
5
elements:
64582
Extracting elements from max heap:
Extracted: 8
Page No: 20
Extracted: 6
Extracted: 5
Extracted: 4
Extracted: 2
ID: 24BQ1A05U9
2024-2028-CSE-E
Vasireddy Venkatadri Institute of Technology
Exp. Name: Graph Traversal - Breadth Date: 2025-09-
[Link]: 4
Page No: 21
First Search 01
Aim:
You are given a string adjacencyMatrix of N [Link] 0's and 1's separated by a space
ID: 24BQ1A05U9
character which are the elements of the adjacency matrix built from an
directed/undirected unweighted graph. Your job is to print the elements of the graph
using Breadth-First Search(BFS).
2024-2028-CSE-E
no_of_vertices: [Link] vertices in the graph
adjacencyMatrix: a string of integer elements of the adjacency matrix of the graph.
Every character '0' or '1' is separated by a space.
Note:
• The elements of the matrix will always be N * N
• Always start the BFS from the first element
• Take the nodes name as 0,1,2,3,....,N always
Example:
Page No: 22
Graph : adjacency
ID: 24BQ1A05U9
matrix of the graph:
2024-2028-CSE-E
adjacencyMatrix: 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0
Explanation:
Here, 0,1,2,3 are the nodes names. It means the BFS is started at 0(zero)
• Visited node 1 from the node 0
• Visited node 2 from the node 1
• Visited node 3 from the node 2 lastly.
Instruction: To complete the required function please follow the function rules given
below, And to run your custom test cases on the terminal please strictly follow the input
and output layout mentioned in the visible sample test case.
Source Code:
CTC15020.c
#include <stdio.h>
Page No: 23
#include <stdlib.h>
#include <string.h>
ID: 24BQ1A05U9
int graph[no_of_vertices][no_of_vertices];
char *token;
int index = 0;
token = strtok(adjacencyMatrix," ");
while(token!=NULL){
graph[index/no_of_vertices][index%
no_of_vertices]=atoi(token);
token=strtok(NULL," ");
index++;
}
int visited[no_of_vertices];
2024-2028-CSE-E
memset(visited,0,sizeof(visited));
int queue[no_of_vertices];
int front = 0,rear =0;
char *result = (char*)malloc(no_of_vertices*4);
result[0]='\0';
queue[rear++]=0;
visited[0]=1;
Page No: 24
char *adjacencyMatrix = argv[2];
printf("%s\n", BreadthFirstSearch(no_of_vertices,
adjacencyMatrix));
return 0;
}
ID: 24BQ1A05U9
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
0 1 2 3
2024-2028-CSE-E
Test Case - 2
User Output
0 1 4 2 3
Page No: 25
First Search 06
Aim:
You are given a string adjacencyMatrix of N [Link] 0's and 1's separated by a space
ID: 24BQ1A05U9
character which are the elements of the adjacency matrix built from an unweighted
graph. Your job is to print the elements of the graph using Depth-First Search(DFS).
2024-2028-CSE-E
adjacencyMatrix: a string of integer elements of the adjacency matrix of the graph
Constraints:
• 0 < no_of_vertices <= 100
Example:
Page No: 26
Graph : adjacency
ID: 24BQ1A05U9
matrix of the graph:
2024-2028-CSE-E
adjacencyMatrix: 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0
Explanation:
Here, 0,1,2,3 are the nodes names and the DFS is started at 0(zero)
• Visited node 1 from the node 0
• Visited node 2 from the node 1
• Visited node 3 from the node 2 lastly.
Instruction: To complete the required function please follow the function rules given
below, And to run your custom test cases on the terminal please strictly follow the input
and output layout mentioned in the visible sample test case.
Source Code:
CTC15028.c
#include <stdio.h>
Page No: 27
#include <stdlib.h>
#include <string.h>
#define MAX_VERTICES 100
void dfs(int vertex,int adj[MAX_VERTICES][MAX_VERTICES],int
visited[MAX_VERTICES],int no_of_vertices,char *result){
ID: 24BQ1A05U9
visited[vertex]=1;
char buffer[10];
sprintf(buffer, "%d ",vertex);
strcat(result, buffer);
for(int i=0;i<no_of_vertices;i++)
{
if((adj[vertex][i]==1)&& !visited[i])
dfs(i,adj,visited,no_of_vertices,result);
}
}
2024-2028-CSE-E
char * depthFirstSearch(int no_of_vertices, char *adjacencyMatrix) {
int adj[MAX_VERTICES][MAX_VERTICES];
int visited[MAX_VERTICES]={0};
char *result = (char *)malloc(500 * sizeof(char));
result[0] = '\0';
char *token = strtok(adjacencyMatrix, " ");
for(int i=0;i<no_of_vertices;i++)
Page No: 28
Test Case - 1
User Output
0 1 2 3
ID: 24BQ1A05U9
Test Case - 2
User Output
0 1 2 3 4
2024-2028-CSE-E
Vasireddy Venkatadri Institute of Technology
Date: 2025-10-
[Link]: 6 Exp. Name: Breadth First Search (BFS)
Page No: 29
06
Aim:
Write a program to implement Breadth First Search (BFS) graph traversal methods.
ID: 24BQ1A05U9
Input Format:
• The first line contains an integer N , the number of vertices in the graph.
• The second line contains an integer E, the number of edges in the graph.
• The next E pairs of lines contain two integers each:
• The first line of each pair contains an integer s representing the source
vertex.
• The second line of each pair contains an integer d representing the
destination vertex.
• The last line contains an integer v, which is the starting vertex for the BFS traversal.
2024-2028-CSE-E
Output Format:
• The program will output the vertices of the graph, each on a new line, in the order
they are visited by the BFS traversal, starting from the vertex v.
Note:
• Driver code is already provided to you in the editor, your task is to fill in the
required code.
GraphsBFS.c
#include <stdio.h>
Page No: 30
#include <stdlib.h>
#define MAX 99
struct node {
int vertex;
ID: 24BQ1A05U9
struct node* next;
};
typedef struct node* GNODE;
GNODE graph[20];
int visited[20];
int queue[MAX], front = -1, rear = -1;
int n;
2024-2028-CSE-E
printf("Queue Overflow.\n");
else {
if (front == -1)
front = 0;
rear++;
queue[rear] = vertex;
}
int isEmptyQueue() {
return (front == -1 || front > rear);
}
int deleteQueue() {
if (isEmptyQueue()) {
printf("Queue Underflow\n");
exit(1);
}
return queue[front++];
}
void BFS(int v) {
int s;
insertQueue(v);
while(!isEmptyQueue())
{
v= deleteQueue();
printf("\n%d",v);
GNODE g = graph[v];
for(;g!=NULL;g= g->next){
Page No: 31
s=g->vertex;
if(visited[s]==0){
insertQueue(s);
visited[s]=1;
}
ID: 24BQ1A05U9
}
}
}
void main() {
int N, E, s, d, i, v;
GNODE p, q;
2024-2028-CSE-E
for (i = 0; i < N; i++) {
graph[i] = NULL;
visited[i] = 0;
}
q = (GNODE)malloc(sizeof(struct node));
q->vertex = d;
q->next = NULL;
if (graph[s] == NULL) {
graph[s] = q;
} else {
p = graph[s];
while (p->next != NULL)
p = p->next;
p->next = q;
}
}
Page No: 32
printf("BFS of graph: ");
BFS(v);
printf("\n");
}
ID: 24BQ1A05U9
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Enter the number of vertices:
5
Enter the number of edges:
2024-2028-CSE-E
5
Enter source:
1
Enter destination:
2
Enter source:
Page No: 33
3
5
Test Case - 2
ID: 24BQ1A05U9
User Output
Enter the number of vertices:
4
Enter the number of edges:
3
Enter source:
1
Enter destination:
2024-2028-CSE-E
2
Enter source:
2
Enter destination:
3
Enter source:
Page No: 34
06
Aim:
Write a program to implement Depth First Search (DFS) graph traversal methods.
ID: 24BQ1A05U9
Input Format:
• The first line of input contains an integer N , the number of vertices in the graph.
• The second line contains an integer E, the number of edges in the graph.
• The next E pairs of lines contain two integers each:
• The first line of each pair contains an integer s representing the source
vertex.
• The second line of each pair contains an integer d representing the
destination vertex.
• The last line contains an integer v, the starting vertex for the DFS traversal.
2024-2028-CSE-E
Output Format:
• The output should display the order of vertices visited during the DFS traversal
starting from the specified vertex v each in a new line.
Note:
• Driver code is already provided to you in the editor, your task is to fill in the
required code.
GraphsDFS.c
#include<stdio.h>
Page No: 35
#include<stdlib.h>
ID: 24BQ1A05U9
struct node* next;
};
// DFS function
void DFS(int i) {
2024-2028-CSE-E
GNODE s = graph[i];
visited[i] = i;
printf("\n%d",i);
while(s!=NULL)
{
int vertex = s->vertex;
if(!visited[vertex])
// Main function
void main() {
int N, E, i, s, d, v;
GNODE q;
// Initialize graph
for (i = 0; i < N; i++) {
graph[i] = NULL;
}
// Input number of edges
Page No: 36
printf("Enter the number of edges: ");
scanf("%d", &E);
// Input edges
for (i = 1; i <= E; i++) {
ID: 24BQ1A05U9
printf("Enter source: ");
scanf("%d", &s);
printf("Enter destination: ");
scanf("%d", &d);
2024-2028-CSE-E
if (graph[s] == NULL)
graph[s] = q;
else {
GNODE p = graph[s];
while (p->next != NULL)
p = p->next;
p->next = q;
Page No: 37
Enter the number of vertices:
6
Enter the number of edges:
7
ID: 24BQ1A05U9
Enter source:
1
Enter destination:
2
Enter source:
1
Enter destination:
4
Enter source:
4
2024-2028-CSE-E
Enter destination:
2
Enter source:
2
Enter destination:
3
Page No: 38
Test Case - 2
User Output
ID: 24BQ1A05U9
Enter the number of vertices:
5
Enter the number of edges:
5
Enter source:
1
Enter destination:
2
Enter source:
2024-2028-CSE-E
1
Enter destination:
4
Enter source:
4
Enter destination:
Page No: 39
User Output
Enter the number of vertices:
4
Enter the number of edges:
ID: 24BQ1A05U9
4
Enter source:
1
Enter destination:
1
Enter source:
1
Enter destination:
3
2024-2028-CSE-E
Enter source:
2
Enter destination:
2
Enter source:
4
Page No: 40
in Graph 15
Aim:
Write a C program to find the number of biconnected components (BCCs) in a given
ID: 24BQ1A05U9
undirected graph.
Input Format:
• The first line contains a single integer, V , the number of vertices in the graph.
• The second line contains a single integer, E, the number of edges.
• Each of the next E lines contains two space-separated integers u and v,
representing an edge between vertex u and vertex v.
Output Format:
• Print a single integer: the number of biconnected components in the graph.
2024-2028-CSE-E
Constraints:
• 1 ≤ V ≤ 1000
• 0 ≤ E ≤ V ∗ (V − 1)/2
• 0 ≤ u, v < V
Source Code:
biConnected.c
Page No: 41
#include <stdlib.h>
#include <limits.h>
typedef struct {
int V;
int** adj;
ID: 24BQ1A05U9
} Graph;
typedef struct {
int x, y;
} Edge;
typedef struct {
Edge* edges;
int size;
int capacity;
} BCCStack;
2024-2028-CSE-E
// Function to create a new graph
Graph* createGraph(int vertices) {
Graph* g = (Graph*)malloc(sizeof(Graph));
g->V = vertices;
g->adj = (int**)malloc(vertices * sizeof(int*));
for (int i = 0; i < vertices; i++) {
ID: 24BQ1A05U9
sizeof(Edge));
}
stack->edges[stack->size].x = u;
stack->edges[stack->size].y = v;
stack->size++;
}
2024-2028-CSE-E
void dfs(Graph *g,int u,int visited[],int disc[],int low[],int
parent[],BCCStack* stack,int* time,int* biConnectedCount){
visited[u]=1;
disc[u]=low[u]=++(*time);
int children=0;
for(int v=0;v<g->V;v++){
if(g->adj[u][v]){
Page No: 43
// Function to find bi-connected components
void findBiConnectedComponents(Graph* g) {
int* disc = (int*)malloc(g->V*sizeof(int));
int* low=(int*)malloc(g->V*sizeof(int));
ID: 24BQ1A05U9
int* parent = (int*)malloc(g->V*sizeof(int));
int* visited=(int*)calloc(g->V,sizeof(int));
BCCStack* stack=createBCCStack(10);
int time=0;
int biConnectedCount=0;
for(int i=0;i<g->V;i++){
parent[i]=-1;
if(!visited[i]){
dfs(g,i,visited,disc,low,parent,stack,&time,&biConnectedCount);
if(stack->size>0){
2024-2028-CSE-E
biConnectedCount++;
while(stack->size>0){
popBCCStack(stack);
}
}
}
}
Graph* g = createGraph(vertices);
//printf("Enter edges (u v):\n");
for (int i = 0; i < edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
addEdge(g, u, v);
}
Page No: 44
findBiConnectedComponents(g);
ID: 24BQ1A05U9
}
free(g->adj);
free(g);
return 0;
}
2024-2028-CSE-E
Test Case - 1
User Output
3
2
01
Test Case - 2
User Output
5
4
01
12
13
24
4
Date: 2025-10-
[Link]: 9 Exp. Name: Implementing Merge Sort
Page No: 45
06
Aim:
Write a C program that implements the merge sort to sort a given array of integers in
ID: 24BQ1A05U9
ascending order, where the function splitAndMerge() for recursive splitting and merging
and the function merge() to combine two sorted sub-arrays.
Input Format:
• The first line of input contains an integer representing the total number of
elements of the array.
• The second line of input contains space-separated integers representing the
elements of the array.
Output Format:
• The first line contains the input array.
2024-2028-CSE-E
• The second line contains the array after sorting.
Note:
• The size of the array is fixed to 15
• Refer to visible test cases to strictly match with the input/output layout.
Source Code:
Page No: 46
void display(int arr[15], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
ID: 24BQ1A05U9
}
2024-2028-CSE-E
int i=0;
int j=0;
int index = low;
while(i<leftArraySize && j<rightArraySize)
{
if(leftArray[i]<=rightArray[j])
{
Page No: 47
return;
int mid = low+(high-low)/2;
splitAndMerge(arr,low,mid);
splitAndMerge(arr,mid+1,high);
merge(arr,low,mid,high);
ID: 24BQ1A05U9
}
void main() {
int arr[15], i, n;
printf("Enter array size: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Before sorting: ");
2024-2028-CSE-E
display(arr, n);
splitAndMerge(arr, 0, n - 1);
printf("After sorting: ");
display(arr, n);
}
User Output
Enter array size:
5
Enter 5 elements:
12354
Before sorting: 1 2 3 5 4
After sorting: 1 2 3 4 5
Test Case - 2
User Output
Enter array size:
8
Enter 8 elements:
95 14 10 2 32 5 9 4
Before sorting: 95 14 10 2 32 5 9 4
Page No: 48
After sorting: 2 4 5 9 10 14 32 95
ID: 24BQ1A05U9
2024-2028-CSE-E
Vasireddy Venkatadri Institute of Technology
Date: 2025-10-
[Link]: 10 Exp. Name: Implementing Quick Sort
Page No: 49
06
Aim:
Write a C program that implements the Quick Sort algorithm to sort a given list of natural
ID: 24BQ1A05U9
numbers in ascending order.
Input Format:
• The first input is an integer n which represents the size of the array.
• The next n inputs are the n natural numbers to be sorted which are space
separated.
Output Format:
• The first line display the elements of the array before sorting, prefixed by: "Before
sorting the elements are :"
• The second line displays the sorted array after sorting, prefixed by: "After sorting
2024-2028-CSE-E
the elements are :"
Source Code:
quickSort.c
Page No: 50
int Partition(int arr[15],int low,int high);
void display(int arr[15],int n){
int i;
for(int i=0;i<n;i++)
printf("%d ",arr[i]);
ID: 24BQ1A05U9
printf("\n");
}
void quickSort(int arr[15],int low,int high){
int pi;
if(low<high){
pi=Partition(arr,low,high);
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
int Partition(int arr[15],int low,int high)
2024-2028-CSE-E
{
int j;
int pivot = arr[high];
int i = low-1;
for(j=low;j<high;j++){
if(arr[j]<=pivot){
i++;
Page No: 51
}
ID: 24BQ1A05U9
Test Case - 1
User Output
Enter array size :
6
Enter 6 elements :
6 2 8 10 36 14
Before sorting the elements are : 6 2 8 10 36 14
After sorting the elements are : 2 6 8 10 14 36
2024-2028-CSE-E
Test Case - 2
User Output
Enter array size :
Page No: 52
with Deadline 15
Aim:
You are given n jobs, where each job has a profit and a deadline. Your task is to schedule
ID: 24BQ1A05U9
the jobs to maximize the total profit such that no two jobs are scheduled at the same
time and each job takes 1 unit of time.
If a job cannot be scheduled before its deadline, it is rejected. The output should display
the job index, profit, deadline, and the slot assigned (or "Rejected" if the job cannot be
scheduled).
Input Format:
First line: An integer n, the number of jobs.
Next 2 × n lines: For each job i (1 ≤ i ≤ n):
• Line 1: Profit of job i (integer)
2024-2028-CSE-E
• Line 2: Deadline of job i (integer)
Output Format:
Print the table with columns:
Index Profit Deadline Slot Alloted
For each job:
• If scheduled, print [start_time - end_time] as the slot allocated in the format that
Constraints:
• 1 ≤ n ≤ 100
• 1 ≤ P rof it ≤ 1000
• 1 ≤ Deadline ≤ 100
Refer to visible test cases for better understanding and to strictly match with the
input/output format and indentations.
Source Code:
jobDeadline.c
#include<stdio.h>
Page No: 53
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
ID: 24BQ1A05U9
*y = temp;
}
int main(){
int n,i,j;
printf("Enter the no of jobs: ");
scanf("%d",&n);
int slot[n],profit,p[n],d[n],maxprofit;
for(i=0;i<n;i++){
printf("Enter the profit of job %d: ",i+1);
scanf("%d",&p[i]);
printf("Enter the deadline of job %d: ",i+1);
2024-2028-CSE-E
scanf("%d",&d[i]);
}
for(int i=0;i<n;i++)
slot[i]=0;
for(i=0;i<n;i++){
int min=i;
for(int j=i+1;j<n;j++){
Page No: 54
for(i=0;i<n;i++){
if(slot[i]>0)
printf("\n%d\t%d \t%d \t[%d - %d]",
i+1,p[i],d[i],(slot[i]-1),slot[i]);else
printf("\n%d\t%d\t%d
ID: 24BQ1A05U9
\tRejected",i+1,p[i],d[i]);
}
}
User Output
2024-2028-CSE-E
Enter the no of jobs:
3
Enter the profit of job 1:
190
Enter the deadline of job 1:
3
Test Case - 2
User Output
Enter the no of jobs:
2
Enter the profit of job 1:
200
Page No: 55
Enter the deadline of job 1:
1
Enter the profit of job 2:
180
ID: 24BQ1A05U9
Enter the deadline of job 2:
1
Index Profit Deadline Slot Alloted
1 200 1 [0 - 1]
2 180 1 Rejected
2024-2028-CSE-E
Vasireddy Venkatadri Institute of Technology
Exp. Name: Dijkstra's Shortest Path Date: 2025-10-
[Link]: 12
Page No: 56
Algorithm 15
Aim:
Given a graph G and source vertex S , Dijkstra's shortest path algorithm is used to find
ID: 24BQ1A05U9
the shortest paths from source S to all vertices in the given graph.
The Dijkstra algorithm is also known as the single-source shortest path algorithm. It is
based on the greedy technique. A little variation in the algorithm can find the shortest
path from the source nodes to all the other nodes in the graph.
The function void dijkstra(int G[M AX][M AX], int n, int startnode) computes and
prints the shortest path distances and corresponding paths from the given source node
to all other nodes in a weighted directed graph using Dijkstra's algorithm. It outputs the
distance or "INF" if unreachable, along with the path or "NO PATH" for each node.
2024-2028-CSE-E
Note:
• Vertices are numbered from 1 through V .
• All input values are separated by spaces and/or newlines.
Dijkstras.c
#include <limits.h>
Page No: 57
#include <stdio.h>
#define MAX 20
int V, E;
int graph[MAX][MAX];
#define INFINITY 99999
ID: 24BQ1A05U9
void dijkstra(int G[MAX][MAX], int n, int startnode) {
int dist[MAX];
int visited[MAX]={0};
int parent[MAX];
int i,j;
for(i=1;i<=V;i++)
{
dist[i]=INFINITY;
parent[i]=-1;
}
2024-2028-CSE-E
dist[startnode]=0;
for(int count=-1;count<=V-1;count++)
{
int min=INFINITY,u=-1;
for(i=1;i<=V;i++){
if(!visited[i]&&dist[i]<=min)
{
Page No: 58
else{
printf(" %d\t",dist[i]);
int temp=i;
printf("%d",i);
while(parent[temp]!=-1)
ID: 24BQ1A05U9
{
printf("<-
%d",parent[temp]);
temp=parent[temp];
}
}
printf("\n");
}
}
}
int main() {
2024-2028-CSE-E
int s, d, w, i, j;
printf("Enter the number of vertices : ");
scanf("%d", &V);
printf("Enter the number of edges : ");
scanf("%d", &E);
for(i = 1 ; i <= V; i++) {
for(j = 1; j <= V; j++) {
Page No: 59
}
ID: 24BQ1A05U9
Test Case - 1
User Output
Enter the number of vertices :
4
Enter the number of edges :
5
Enter source :
1
2024-2028-CSE-E
Enter destination :
2
Enter weight :
4
Enter source :
1
Page No: 60
2
Enter the source :
1
Node Distance Path
ID: 24BQ1A05U9
2 4 2<-1
3 6 3<-1
4 8 4<-3<-1
Test Case - 2
User Output
Enter the number of vertices :
5
2024-2028-CSE-E
Enter the number of edges :
6
Enter source :
1
Enter destination :
2
Page No: 61
4
Enter destination :
3
Enter weight :
ID: 24BQ1A05U9
2
Enter source :
5
Enter destination :
4
Enter weight :
1
Enter the source :
2
2024-2028-CSE-E
Node Distance Path
1 INF NO PATH
3 6 3<-4<-2
4 4 4<-2
5 INF NO PATH
User Output
Enter the number of vertices :
4
Enter the number of edges :
5
Enter source :
1
Enter destination :
2
Enter weight :
4
Enter source :
3
Enter destination :
2
Enter weight :
Enter source :
4
Page No: 62
Enter destination :
1
Enter weight :
1
ID: 24BQ1A05U9
Enter source :
4
Enter destination :
2
Enter weight :
3
Enter source :
4
Enter destination :
2024-2028-CSE-E
3
Enter weight :
8
Enter the source :
1
Node Distance Path
Page No: 63
Dynamic programming 15
Aim:
Write a program to implement Knapsack using Dynamic programming
ID: 24BQ1A05U9
Source Code:
DynamicKnapsack.c
#include<stdio.h>
int max(int a,int b){
return(a>b)?a:b;
}
int knapsack(int W,int wt[],int val[],int n){
int dp[n+1][W+1];
for(int i=0;i<=n;i++){
2024-2028-CSE-E
for(int w=0;w<=W;w++){
if(i==0||w==0)
dp[i][w]=0;
else if(wt[i-1]<=w)
dp[i][w]=max(val[i-1]+dp[i-1][w-wt[i-
1]],dp[i-1][w]);
else
Page No: 64
Test Case - 1
User Output
Enter the no. of items:
ID: 24BQ1A05U9
3
Enter the weight and price of all items
10 60
20 100
30 120
enter the capacity of knapsack:
50
The maximum value of items that can be put into knapsack is: 220
2024-2028-CSE-E
Test Case - 2
User Output
Enter the no. of items:
3
Enter the weight and price of all items
Page No: 65
backtracking 15
Aim:
N-Queens using Backtracking:
ID: 24BQ1A05U9
Here is an algorithm for solving the N-Queens problem using backtracking:
1. Start with an empty chessboard of size N x N.
2. Place the first queen in the leftmost column of the first row.
3. Move to the next row and try to place a queen in an empty square in that row that is
not attacked by any of the queens already placed on the board.
4. If a queen can be placed in the current row, move to the next row and repeat step 3.
5. If a queen cannot be placed in the current row, backtrack to the previous row and try
a different square in that row. If all squares in the previous row have been tried and
none of them worked, backtrack again to the previous row.
6. Repeat steps 3-5 until all N queens have been placed on the board or it is determined
2024-2028-CSE-E
that no solution exists.
The key to this algorithm is the "not attacked" rule. To determine whether a queen is
being attacked by any other queen on the board, we need to check whether any other
queen is in the same row, column, or diagonal as the current queen.
Input Format:
It contains the number of queens in an Array.
Output Format:
An array in which the queens are placed and print a*symbol when there is no queen in
that particular row or column. You need to print all the possible solutions based on the
input and display the Total no of solutions. If there are no solutions then print the
solution as 0.
Constraints:
1 <= N <= 6
Source Code:
nQueen.c
#include<stdio.h>
Page No: 66
#define N 10
int arr[N][N];
void print(int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
ID: 24BQ1A05U9
if(arr[i][j]==0)
printf("*\t");
else
printf("Q\t");
}
printf("\n");
}
}
int check(int r,int c,int n){
int dr=r;
int dc=c;
2024-2028-CSE-E
while(dr>=0 && dc>=0){
if(arr[dr][dc]==1)
return 0;
dr--;
dc--;
}
dr=r;
Page No: 67
}
for(int i=0;i<n;i++)
{
if(check(row,i,n))
{
ID: 24BQ1A05U9
arr[row][i]=1;
placing(n,row+1,count);
arr[row][i]=0;
}
}
}
void main(){
int n;
scanf("%d",&n);
int count=0;
for(int i=0;i<n;i++){
2024-2028-CSE-E
for(int j=0;j<n;j++){
arr[i][j]=0;
}
}
placing(n,0,&count);
printf("Total solutions:%d\n",count);
}
User Output
4
Solution #1:
* Q * *
* * * Q
Q * * *
* * Q *
Solution #2:
* * Q *
Q * * *
* * * Q
* Q * *
3
User Output
Total solutions:0
Total solutions:2
Test Case - 2
Page No: 69
backtracking 15
Aim:
Write a C program to solve the 0/1 Knapsack Problem using backtracking approach. The
ID: 24BQ1A05U9
program aims to maximize the total value of items that can be included in a knapsack
without exceeding its capacity
Input Format:
Output Format:
2024-2028-CSE-E
• Print the maximum profit (total value) that can be obtained by selecting items,
considering the knapsack's capacity constraint.
Source Code:
knapsackBacktracking.c
Page No: 70
#include <stdlib.h>
ID: 24BQ1A05U9
for(int w=0;w<=capacity;w++)
{
if(i==0||w==0)
{
dp[i][w]=0;
}
else if(weights[i-1<=w]){
int include=values[i-1]+dp[i-1]
[w-weights[i-1]];
int exclude=dp[i-1][w];
dp[i][w]=(include>exclude)?
2024-2028-CSE-E
include:exclude;
}
else{
dp[i][w]=dp[i-1][w];
}
}
}
int main() {
int n;
int capacity;
scanf("%d", &capacity);
// Calculate and print the maximum profit
Page No: 71
printf("%d\n", knapsack(weights, values, capacity, n));
ID: 24BQ1A05U9
return 0;
}
User Output
2024-2028-CSE-E
3
60 10
100 20
120 30
50
Test Case - 2
User Output
5
10 5
40 4
30 3
50 2
20 1
100
150
Exp. Name: Problem on Travelling Date: 2025-10-
[Link]: 16
Page No: 72
Salesman 15
Aim:
A traveler needs to visit all the cities from a given list of cities, where the distances
ID: 24BQ1A05U9
between the cities are known. The traveler must start at the origin city (City 1), visit each
city exactly once, and then return to the origin city. The goal is to determine the shortest
possible route and its total travel cost using a Branch and Bound technique.
You are given the number of cities and the cost matrix, where the value in the matrix at
position [i][j] represents the travel cost between city i and city j. A value of 0 in the
matrix means there is no travel cost between a city and itself.
Task:
• Find the shortest route that visits all cities exactly once and returns to the starting
city.
2024-2028-CSE-E
• Print the sequence of cities in the shortest path.
• Print the total minimum cost of this route.
Input Format:
• The first line contains an integer n representing the number of cities.
• The next n lines contain n integers each, representing the cost matrix C , where
C[i][j] denotes the cost of traveling from city i to city j. The integers are
Output Format:
• An integer representing the total minimum cost of traveling through a shortest
path.
Constraints:
• 2 ≤ n ≤ 25
• The cost matrix will always be symmetric, i.e., C[i][j] == C[j][i] ] and C[i][j] = 0 .
Source Code:
CTC36670.c
#include<stdio.h>
Page No: 73
#include<stdlib.h>
#include<limits.h>
#define MAX 25
#define INF INT_MAX
int n;
ID: 24BQ1A05U9
int cost[MAX][MAX];
int best_cost=INF;
int best_path[MAX];
int current_path[MAX];
void tsp(int current_pos,int count,int cost_so_far){
if(count==n && cost[current_pos][0]>0){
if(cost_so_far + cost[current_pos][0]<best_cost){
best_cost=cost_so_far + cost[current_pos][0];
for(int i=0;i<n;i++)
best_path[i]=current_path[i];
best_path[n]=0;
2024-2028-CSE-E
}
return;
}
for(int next_pos=0;next_pos <n;next_pos++){
if(cost[current_pos][next_pos]>0 &&
(current_path[next_pos]==-1)){
current_path[next_pos]=count;
60
15 35 0
10 0 35
0 10 15
User Output
Test Case - 1