You are on page 1of 28

SAGE UNIVERSITY INDORE

DEPARTMENT OF CSE/IT

Lab Manual
(2023-24)
*Analysis and Design of Algorithms Lab*
(ECSDEADA001P)

Submitted to Submitted By
Prof. Name
Designation Enl. No.
INDEX
S. NO LIST OF EXPRIEMENTS DATE REMARKS SINATURE

1. Write a Program to implement Iterative &


Recursive Binary Search Algorithm.

2. Write a Program to implement Merge Sort


Algorithm.

3. Write a program to implement Quick Sort


Algorithm.

4. Write a program to implement Heap Sort


Algorithm.

5. Write a Program to implement Depth First


Search Algorithm.

6. Write a Program to implement Breadth First


Search Algorithm.

7. Write a Program to find Minimum Spanning


Tree using Kruskal's algorithm.

8. Write a Program to find Minimum Spanning


Tree using Prim's algorithm.

9. Implement 0/1 Knapsack problem using


Dynamic Programming.

10. Implement the Traveling Salesperson


problem using Branch & Bound Technique.
Experiment No: 1

Aim: Write a Program to implement Iterative & Recursive Binary Search


Algorithm.

Working

The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.

Case 1 − element = middle, the element is found return the index.

Case 2 − element > middle, search for the element in the sub-array starting from middle+1 index
to n.

Case 3 − element < middle, search for element in the sub-array starting from 0 index to middle -
1.

ALGORITHM

Parameters inital_value ,end_value

Step 1 : Find the middle element of array. using ,


middle = initial_value + end_value / 2 ;
Step 2 : If middle = element, return „element found‟ and index.
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.

Program

#include<stdio.h>
intiterativeBinarySearch(int array[],intstart_index,intend_index,int element){
while(start_index<=end_index){
int middle =start_index+(end_index-start_index)/2;
if(array[middle]== element)
return middle;
if(array[middle]< element)
start_index= middle +1;
else
end_index= middle -1;
}
return-1;
}
int main(void){
intarray[]={1,4,7,9,16,56,70};
int n =7;
int element =16;
intfound_index=iterativeBinarySearch(array,0, n-1, element);
if(found_index==-1){
printf("Element not found in the array ");
}
else{
printf("Element found at index : %d",found_index);
}
return0;
}

Output
Element found at index: 4

Program

Program To Implement Binary Search Using Recursive Call

#include<stdio.h>
intrecursiveBinarySearch(int array[],intstart_index,intend_index,int element){
if(end_index>=start_index){
int middle =start_index+(end_index-start_index)/2;
if(array[middle]== element)
return middle;
if(array[middle]> element)
returnrecursiveBinarySearch(array,start_index, middle-1, element);
returnrecursiveBinarySearch(array, middle+1,end_index, element);
}
return-1;
}
int main(void){
intarray[]={1,4,7,9,16,56,70};
int n =7;
int element =9;
intfound_index=recursiveBinarySearch(array,0, n-1, element);
if(found_index==-1){
printf("Element not found in the array ");
}
else{
printf("Element found at index : %d",found_index);
}
return0;
}
Output
Element found at index: 3
Experiment No: 2

Aim: Write a Program to implement Merge Sort Algorithm.


Program:

#include<stdio.h>
#include<conio.h>
void merge(int[],int,int,int);
void mergesort(int[], int,int);
void merge(int a[25], int low, int mid, int high)
{
int b[25],h,i,j,k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}
void mergesort(int a[25],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a, low,mid,high);
}
}
void main()
{
int a[25],i,n;
clrscr();
printf("\n Enter the size of the elements to be sorted:");
scanf("%d",&n);
printf("\n Enter the elements to sort:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n The Elements before sorting are:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
mergesort(a, 0,n-1);
printf("\n The elements after sorting are:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
Output:
Experiment No: 3

Aim: Write a program to implement Quick Sort Algorithm.

Program:
#include<stdio.h>
#include<conio.h>
void qsort(int [],int,int);
int partition(int [],int,int);
void qsort(int a[],int first,int last)
{
int j;
if(first<last)
{
j=partition(a,first,last+1);
qsort(a,first,j-1);
qsort(a,j+1,last);
}
}
int partition(int a[],int first,int last)
{
int v=a[first];
int i=first;
int j=last;
int temp=0;
do
{
do
{
i++;
}while(a[i]<v);
do
{
j--;
}while(a[j]>v);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[first]=a[j];
a[j]=v;
return j;
}
int main()
{
int a[40],i,n;
clrscr();
printf("\n Enter the no of elements (size):");
scanf("%d",&n);
printf("\n Enter the ELements to sort:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,0,n-1);
printf("\n The ELements after sorting are:");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
return 0;
}

Output:
Experiment No: 4

Aim: Write a program to implement Heap Sort Algorithm.

#include <stdio.h>
voidswap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
voidheapify(intarr[], int n, inti)
{
int left, right, largest;
largest = i;
left = 2 * i + 1;
right = 2 * i + 2;
// Check if left child exists and is larger than its parent
if (left < n &&arr[left] >arr[largest])
largest = left;
// Check if right child exists and larger than its parent
if (right < n &&arr[right] >arr[largest])
largest = right;
// if root is not the largest
if (largest != i) {
swap(&arr[i], &arr[largest]); //make root the largest
heapify(arr, n, largest); // Apply heapify to the largest node
}
}
voidheap_sort(intarr[], int n)
{
inti;
for (i = (n / 2) - 1; i>= 0; i--)
heapify(arr, n, i);
for (i = n - 1; i>= 0; i--) {
swap(&arr[0], &arr[i]); //Move the largest element at root to the end
heapify(arr, i, 0); //Apply heapify to reduced heap
}
}
intmain()
{
intarr[] = { 20, 13, 34, 56, 12, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array:\n");
for (inti = 0; i< n; i++)
printf("%d ", arr[i]);
heap_sort(arr, n);

printf("\nAfter performing Heap Sort:\n");


for (inti = 0; i< n; i++)
printf("%d ", arr[i]);

return0;
}
Output:
Experiment No: 5

Aim: Write a Program to implement Breadth First Search Algorithm.


// BFS algorithm in C

#include<stdio.h>
#include<stdlib.h>
#define SIZE 40

structqueue {
intitems[SIZE];
int front;
int rear;
};
struct queue* createQueue();
voidenqueue(struct queue* q, int);
intdequeue(struct queue* q);
voiddisplay(struct queue* q);
intisEmpty(struct queue* q);
voidprintQueue(struct queue* q);

structnode {
int vertex;
structnode* next;
};
struct node* createNode(int);

structGraph {
intnumVertices;
structnode** adjLists;
int* visited;
};
// BFS algorithm
voidbfs(struct Graph* graph, intstartVertex){
structqueue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while(!isEmpty(q)) {
printQueue(q);
intcurrentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
structnode* temp = graph->adjLists[currentVertex];
while (temp) {
intadjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v){
structnode* newNode = malloc(sizeof(structnode));
newNode->vertex = v;
newNode->next = NULL;
returnnewNode;
}
// Creating a graph
struct Graph* createGraph(int vertices){
structGraph* graph = malloc(sizeof(structGraph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));


graph->visited = malloc(vertices * sizeof(int));

inti;
for (i = 0; i< vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
voidaddEdge(struct Graph* graph, intsrc, intdest){
// Add edge from src to dest
structnode* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Create a queue
struct queue* createQueue(){
structqueue* q = malloc(sizeof(structqueue));
q->front = -1;
q->rear = -1;
return q;
}

// Check if the queue is empty


intisEmpty(struct queue* q){
if (q->rear == -1)
return1;
else
return0;
}

// Adding elements into queue


voidenqueue(struct queue* q, int value){
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}

// Removing elements from queue


intdequeue(struct queue* q){
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


voidprintQueue(struct queue* q){
inti = q->front;

if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i< q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

intmain(){
structGraph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);

bfs(graph, 0);

return0;
}
Experiment No: 6

Aim: Write a Program to implement Depth First Search Algorithm.


#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);
//read the adjecency matrix
printf("\nEnteradjecency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
Experiment No: 7

Aim: Write a Program to find Minimum Spanning Tree using Kruskal's algorithm.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];

int find(int);
int uni(int, int);

void main()
{
printf("Kruskal's algorithm in C\n");
printf("========================\n");

printf("Enter the no. of vertices:\n");


scanf("%d", &n);

printf("\nEnter the cost adjacency matrix:\n");


for (i = 1; i<= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
cost[i][j] = 999;
}
}

printf("The edges of Minimum Cost Spanning Tree are\n");


while (ne < n)
{
for (i = 1, min = 999; i<= n; i++)
{
for (j = 1; j <= n; j++)
{
if (cost[i][j] < min)
{
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}

u = find(u);
v = find(v);

if (uni(u, v))
{
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
mincost += min;
}

cost[a][b] = cost[b][a] = 999;


}

printf("\nMinimum cost = %d\n", mincost);


getch();
}

int find(int i)
{
while (parent[i])
i = parent[i];
return i;
}

int uni(int i, int j)


{
if (i != j)
{
parent[j] = i;
return 1;
}

return 0;
}
Experiment No: 8

Aim: Write a Program to find Minimum Spanning Tree using 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;
}
//initialise visited[],distance[] and from[]
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; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
Experiment No: 9

Aim: Implement 0/1 Knapsack problem using Dynamic Programming.


#include<stdio.h>
/* Function to find maximum of two integers */
int max(int a, int b) { return (a > b)? a : b; }
/* Function to find the maximum value that can be put in a knapsack of capacity W */
int knapSack(int W, int weight[], int value[], int n)
{
if (n == 0 || W == 0) /* Base Case */
return 0;
/* If weight of the nth item is more than Knapsack capacity W */
if (weight[n-1] > W)
return knapSack(W, weight, value, n-1); /* this item cannot be included in the optimal solution */
else return max( value[n-1] + knapSack(W-weight[n-1], weight, value, n-1), knapSack(W,
weight, value, n-1));
}
int main()
{
int n;
printf(“\nEnter the number of items : “);
scanf(“%d”, &n);
int value[n];
int weight[n];
int i;
printf(“\nEnter the item‟s weight and its value \n”);
for(i = 0; i< n; i++)
{
scanf(“%d %d”, &weight[i], &value[i]);
}
int W;
printf(“\nEnter the capacity of the knapsack : “);
scanf(“%d”, &W);
printf(“\nMaximum value in a 0-1 knapsack : %d\n”, knapSack(W, weight, value, n));
return 0;
}
Experiment No: 10

Aim:Implement the Traveling Salesperson problem using Branch & Bound


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

#define N 4 // Number of cities

int graph[N][N] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < N; v++) {
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
int primMST(int graph[N][N]) {
int parent[N];
int key[N];
bool mstSet[N];
for (int i = 0; i< N; i++) {
key[i] = INT_MAX;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < N - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;

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


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

int mstWeight = 0;
for (int i = 1; i< N; i++) {
mstWeight += graph[i][parent[i]];
}
return mstWeight;
}
int firstMin(int i, int graph[N][N]) {
int min = INT_MAX;
for (int k = 0; k < N; k++)
if (i != k && graph[i][k] < min)
min = graph[i][k];
return min;
}
int secondMin(int i, int graph[N][N]) {
int first = INT_MAX, second = INT_MAX;
for (int j = 0; j < N; j++) {
if (i != j) {
if (graph[i][j] <= first) {
second = first;
first = graph[i][j];
} else if (graph[i][j] <= second && graph[i][j] != first) {
second = graph[i][j];
}
}
}
return second;
}
void TSPRec(int curr_bound, int curr_weight, int level, int parent[], bool visited[N], int
graph[N][N]) {
if (level == N - 1) {
if (graph[parent[level - 1]][level] != 0) {
int current_pathweight = curr_weight + graph[parent[level - 1]][level];

if (current_pathweight<curr_bound) {
printf("Path: ");
for (int i = 0; i< N; i++) {
printf("%d ", parent[i]);
}
printf("%d\n", level);
printf("Cost: %d\n", current_pathweight);
printf("-------------\n");
}
}
return;
}
for (int i = 0; i< N; i++) {
if (!visited[i] && graph[parent[level - 1]][i] != 0) {
int temp = curr_bound;
curr_weight += graph[parent[level - 1]][i];

if (level == 1)
curr_bound -= (firstMin(parent[level - 1], graph) + firstMin(i, graph)) / 2;
else
curr_bound -= (secondMin(parent[level - 1], graph) + firstMin(i, graph)) / 2;

if (curr_bound + curr_weight< temp) {


parent[level] = i;
visited[i] = true;
TSPRec(curr_bound, curr_weight, level + 1, parent, visited, graph);
}
curr_weight -= graph[parent[level - 1]][i];
curr_bound = temp;

for (int j = 0; j < N; j++)


visited[j] = false;
for (int j = 0; j <= level - 1; j++)
visited[parent[j]] = true;
}
}
}
void TSP(int graph[N][N]) {
int parent[N];
bool visited[N];

int curr_bound = primMST(graph);


for (int i = 0; i< N; i++) {
parent[i] = -1;
visited[i] = false;
}
visited[0] = true;
parent[0] = 0;

TSPRec(curr_bound, 0, 1, parent, visited, graph);


}
int main() {
TSP(graph);

return 0;
}

Output
Path: 0 1 2 3
Cost: 80
-------------
Path: 0 2 1 3
Cost: 80

You might also like