DAA Lab Programs
DAA Lab Programs
#include <stdio.h>
*xp = *yp;
*yp = temp;
int i, j, min_idx;
min_idx = i;
min_idx = j;
if(min_idx != i)
swap(&arr[min_idx], &arr[i]);
int i;
printf("\n");
int main()
{
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printArray(arr, n);
return 0;
AIM
ALGORITHM
The travelling salesman Algorithm states that - " From a given set of N cities and distance
between each pair of the cities, find the minimum path length in such a way that it covers each
and every city exactly once (without repletion of any path) and terminate the traversal at the
starting point or the starting city from where the traversal of the TSP Algorithm was initiated.
1) A cost variable and visited array will be used to keep track of the updated minimum cost and
whether a node is already visited or not
2)Start with a source vertex, mark it visited, find the next neighbor node with minimum cost.
3)If any of the neighbor nodes are unvisited, find the node with minimum distance and add it to
the cost variable.
4) Recur for the found next nodes till a next node is found with zero neighbors unvisited
PROGRAM
#include <stdio.h>
#include<limits.h>
int graph[10][10] = {
{12, 30, 33, 10, 45},
{56, 22, 9, 15, 18},
{29, 13, 8, 5, 12},
{33, 28, 16, 10, 3},
{1, 4, 30, 24, 20}
};
int visited[10], n, cost = 0;
/* main function */
int main()
{
int i, j;
n = 5;
for(i = 0; i < n; i++)
{
visited[i] = 0;
}
printf("Shortest Path: ");
TSP(0);
printf("\nMinimum Cost: ");
printf("%d\n", cost);
return 0;
}
RESULT
AIM
Write program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem.
ALGORITHM
Given N items where each item has some weight and profit associated with it and also given a
bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the
items into the bag such that the sum of profits associated with them is the maximum
possible.
The constraint here is we can either put an item completely into the bag or cannot put it at all
[It is not possible to put a part of an item into the bag].
PROGRAM
#include <stdio.h>
return K[n][W];
}
int main()
{
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("Knapsack problem using dynamic programming...\n");
printf("\nMaximum Profit or Value = %d", knapsack(W, wt, val, n));
return 0;
}
RESULT
ALGORITHM
Given the weights and profits of N items, in the form of {profit, weight} put these items in a
knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional
Knapsack, we can break items for maximizing the total value of the knapsack.
Take the item with highest ratio and add them until we can't add the next item as whole
PROGRAM
#include<stdio.h>
int main()
{
for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
RESULT
Thus the given task is completed successfully.
Ex. no. 5a Breadth First Traversal
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// No. of vertices
int V;
bool adj[10][10];
} Graph;
Graph* Graph_create(int V)
{
Graph* G = malloc(sizeof(Graph));
G->V = V;
{
G->adj[i][j] = false;
}
}
return G;
}
// Driver code
int main()
{
// Create a graph
Graph* G = Graph_create(4);
Graph_addEdge(G, 0, 1);
Graph_addEdge(G, 0, 2);
Graph_addEdge(G, 1, 2);
Graph_addEdge(G, 2, 0);
Graph_addEdge(G, 2, 3);
Graph_addEdge(G, 3, 3);
return 0;
}
return G;
}
// Driver code
void main()
{
struct Graph* G;
G = adjMatrix();
DFStraversal(G);
}
RESULT
Thus the given task is completed successfully.
EX. No. 7 QUIK SORT USING DIVIDE AND CONQUER
AIM
Write a test program to implement Divide and Conquer strategy. Eg : Quick sort
algorithm for sorting list of integer in ascending order.
ALGORITHM
Quicksort(A[l..r])
//Input: Subarray of array A[0..n −1], defined by its left and right
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s−1])
Quicksort(A[s + 1..r])
Partition(A[l..r])
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
p ← A[l] i ← l;
j←r+1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j − 1 until A[j ] ≤ p
swap(A[i], A[j ])
until i ≥ j
swap(A[i], A[j ]) //undo last swap when i ≥ j
swap(A[l], A[j ])
return j
PROGRAM
/* Quik sort using divide and conquer*/
#include<stdio.h>
int main()
{
int A[15],n,i;
printf("Enter the total number of elements\n");
scanf("%d",&n);
quickSort(A,0,n-1);
printf("Sorted Array\n");
for( i=0;i<n;i++)
printf("%d\n",A[i]);
return 0;
}
RESULT
Thus the given task is completed successfully.
EX. No. 8 MERGE SORT USING DIVIDE AND CONQUER
AIM
Write a program to implement merge sort algorithm for sorting list of integer in
ascending order.
ALGORITHM
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop
PROGRAM
// l is for left index and r is right index of the sub-array of array to be sorted
void mergeSort(int A[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for large l and r
int m = l + (r - l) / 2;
int main()
{
int A[15],n,i;
printf("Enter the total number of elements\n");
scanf("%d",&n);
printf("Enter the elements one by one\n");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
mergeSort(A, 0, n-1);
printf("Sorted Array\n");
for( i=0;i<n;i++)
printf("%d\n",A[i]);
getch();
return 0;
RESULT
Thus the given task is completed successfully.
EX. No. 9 MERGE SORT with n>5000
AIM
Sort a given set of n integer elements using Merge sort method and compute its time
complexity. Run the Program for varied values of n>5000, and record the time taken to sort.
ALGORITHM
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop
PROGRAM
// l is for left index and r is right index of the sub-array of array to be sorted
int main()
{
int A[6000],n,i;
RESULT
Thus the given task is completed successfully.
EX. No. 10 QUICK SORT with n>5000
AIM
Sort a given set of n integer elements using quick sort method and compute its time
complexity. Run the Program for varied values of n>5000, and record the time taken to sort.
ALGORITHM
Quicksort(A[l..r])
//Input: Subarray of array A[0..n −1], defined by its left and right
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s−1])
Quicksort(A[s + 1..r])
Partition(A[l..r])
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
p ← A[l] i ← l;
j←r+1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j − 1 until A[j ] ≤ p
swap(A[i], A[j ])
until i ≥ j
swap(A[i], A[j ]) //undo last swap when i ≥ j
swap(A[l], A[j ])
return j
PROGRAM
/* Quik sort using divide and conquer*/
#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
#include <time.h>
for(int j=low;j<=high;j++)
{
/*If current element is smaller than the pivot Increment index of smaller element*/
if(A[j]<pivot)
{
i++;
temp= A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp = A[i+1];
A[i+1]=A[high];
A[high]=temp;
return (i+1);
}
void quickSort(int A[],int low,int high)
{
if(low<high)
{
int pi=partition(A,low,high);
quickSort(A,low,pi-1);
quickSort(A,pi+1,high);
}
}
int main()
{
int A[6000],n,i;
quickSort(A,0,5000);
printf("Sorted Array\n");
for( i=0;i<5001;i++)
printf("%d ",A[i]);
getch();
return 0;
}
RESULT
Thus the given task is completed successfully.
PART -B
AIM
Write a C Program that accepts the vertices and edges for a graph and stores it as an
adjacency matrix.
ALGORITHM
Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also
used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j
with weight w.
Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges),
it consumes the same space. Adding a vertex is O(V^2) time.
PROGRAM
/*program to accept vertices and edges of a graph and prints its adjacency matrix*/
#include<stdio.h>
#include<conio.h>
int main()
{
int adj[10][10]; // adjacency matrix
int n;// number of vertices
int max_edges,origin,destin,i,j;
adj[destin][origin] = 1;
}
}
RESULT
OUTPUT
AIM
Implement function to print In-Degree, Out-Degree and to display that adjacency matrix.
ALGORITHM
Given a directed graph, the task is to count the in and out degree of each vertex of the
graph.
The total count of incoming edges to a particular vertex is known as the indegree of that
vertex, and the total number of outgoing edges from a particular vertex is known as the
outdegree of that vertex.
PROGRAM
/*Implement function to print in - degree and out degree and to display that adjacency matrix.*/
#include<stdio.h>
#include<conio.h>
#define MAX 10
void accept_graph(int G[][MAX], int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Edge (V%d,V%d) exists? (Yes=1, No=0):",i,j);
scanf("%d",&G[i][j]);
}
}
}
void disp_adj_mat(int G[][MAX], int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%4d",G[i][j]);
}
printf("\n");
}
}
void main()
{
int G[MAX][MAX],n;
printf("Enter no.ofvertices:");
scanf("%d",&n);
accept_graph(G,n);
printf("Adjacency Matrix:\n");
disp_adj_mat(G,n);
printf("Out degree:\n");
calc_out_degree(G,n);
printf("In degree:\n");
calc_in_degree(G,n);
}
RESULT
OUTPUT
Adjacency Matrix:
10
10
Out degree:
out-deg(V0)=1
out-deg(V1)=1
In degree:
in-deg(V0)=2
in-deg(V1)=0
Ex.No.3 N QUEENS
AIM
Write program to implement backtracking algorithm for solving problems like N queens.
ALGORITHM
The N Queen is the problem of placing N chess queens on an N×N chessboard so that
no two queens attack each other.
For example, the following is a solution for the 4 Queen problem.
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed queens.
In the current column, if we find a row for which there is no clash, we mark this row and
column as part of the solution. If we do not find such a row due to clashes, then we backtrack
and return false.
Step 1: Start in the leftmost column. If all queens are placed return true
Step 2: Try all rows in the current column. Do the following steps for every row.
Step 4: If placing the queen in [row, column] leads to a solution then return true.
Step 5: If placing queen doesn’t lead to a solution then unmark this [row, column] then
backtrack and try other rows.
If all rows have been tried and valid solution is not found return false to trigger
backtracking.
PROGRAM
/* A utility function to check if a queen can be placed on board[row][col]. Note that this function is
called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left
side for attacking queens */
return true;
}
/* Consider this column and try placing this queen in all rows one by one */
for (int i = 0; i < N; i++)
{
/* Check if the queen can be placed on board[i][col] */
if (isSafe(board, i, col))
{
/* Place this queen in board[i][col] */
board[i][col] = 1;
/* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens cannot be placed, otherwise, return true and
prints placement of queens in the form of 1s. Note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false)
{
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
int main()
{
solveNQ();
return 0;
}
RESULT
OUTPUT
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Ex.No.4 SUM OF SUBSETS
AIM
Write a program to implement the backtracking algorithm for the sum of subsets
problem
ALGORITHM
PROBLEM STATEMENT
Given an array of integers and a sum, the task is to have all subsets of given array with
sum equal to the given sum.
In the subset sum problem, we have to find the subset of a set is such a way that the
element of this subset-sum up to a given number K. All the elements of the set are positive and
unique (no duplicate elements are present).
For this, we will create subsets and check if their sum is equal to the given number k
Subset sum can also be thought of as a special case of the 0–1 Knapsack problem. For each
item, there are two possibilities
case 1: Include the current element in the subset and recur for the remaining elements with the
remaining Sum.
case 2: Exclude the current element from the subset and recur for the remaining elements.
Finally, if Sum becomes 0 then print the elements of current subset. The recursion’s base case
would be when no items are left, or the sum becomes negative, then simply return.
Begin
if total = sum, then
display the subset
//go for finding next subset
subsetSum(set, subset, , subSize-1, total-set[node], node+1, sum)
return
else
for all element i in the set, do
subset[subSize] := set[i]
subSetSum(set, subset, n, subSize+1, total+set[i], i+1, sum)
done
End
PROGRAM
/*program to implement the backtracking algorithm for the sum of subsets problem */
#include <stdio.h>
#include <stdlib.h>
void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum)
{
if (target_sum == sum)
{
printValues(t, t_size);
subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);
return;
}
else
{
for (int i = ite; i < s_size; i++)
{
t[t_size] = s[i];
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}
int main()
{
int set[] = { 1,2,3,4 };
int size = sizeof(set) / sizeof(set[0]);
printf("\n The set is :");
printValues(set , size);
printf("Given sum is : 7\n");
printf("\n The subsets are :\n");
generateSubsets(set, size, 7);
return 0;
}
RESULT
OUTPUT
The set is : 1 2 3 4
Given sum is : 7
AIM
Write program to implement greedy algorithm for job sequencing with deadlines.
ALGORITHM
The greedy approach of the job scheduling algorithm states that, “Given ‘n’ number of
jobs with a starting time and ending time, they need to be scheduled in such a way that
maximum profit is received within the maximum deadline”.
Set of jobs with deadlines and profits are taken as an input with the job scheduling
algorithm and scheduled subset of jobs with maximum profit are obtained as the final output.
Step1 : Find the maximum deadline value from the input set of jobs.
Step2 : Once, the deadline is decided, arrange the jobs in descending order of their
profits.
Step3 : Selects the jobs with highest profits, their time periods not exceeding the
maximum deadline.
Step4 : The selected set of jobs are the output.
PROGRAM
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Driver's code
int main()
{
Job arr[] = { { 'a', 2, 100 },
{ 'b', 1, 19 },
{ 'c', 2, 27 },
{ 'd', 1, 25 },
{ 'e', 3, 15 } };
int n = sizeof(arr) / sizeof(arr[0]);
printf( "Following is maximum profit sequence of jobs \n");
// Function call
printJobScheduling(arr, n);
return 0;
}
RESULT
OUTPUT
Write program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.
ALGORITHM
An Optimal Binary Search Tree is a variant of binary search trees where the arrangement of
nodes is strategically optimized to minimize the cost of searches. The key idea behind an OBST
is to place frequently accessed items closer to the root, reducing the search time for those
elements. Conversely, less frequently accessed items are placed further away, leading to a
balanced and efficient search tree
Begin
define cost matrix of size n x n
for i in range 0 to n-1, do
cost[i, i] := freq[i]
done
{
for (int i=0; i<=n-length+1; i++)
{ //from 0th row to n-length+1 row as i
int j = i+length-1;
cost[i][j] = INT_MAX; //initially store to maximum value
int main() {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = 3;
printf("Cost of Optimal BST is: %d ", minCostBST(keys, freq, n));
}
RESULT
OUTPUT
AIM
Write a program that implements Prim's algorithm to generate minimum cost spanning
Tree.
ALGORITHM
Step 1: Initialize the minimum spanning tree with a vertex chosen at random.
Step 2: Find all the edges that connect the tree to new vertices, find the minimum and add it to
the tree
Step 3: Keep repeating step 2 until we get a minimum spanning tree
PROGRAM
#include <stdio.h>
#include <limits.h>
#define vertices 5 /*Define the number of vertices in the graph*/
/* create minimum_key() method for finding the vertex that has minimum key-value and that is
not added in MST yet */
int minimum_key(int k[], int mst[])
{
int minimum = INT_MAX, min,i;
/*iterate over all vertices to find the vertex with minimum key-value*/
for (i = 0; i < vertices; i++)
if (mst[i] == 0 && k[i] < minimum )
minimum = k[i], min = i;
return min;
}
/* create prim() method for constructing and printing the MST.
The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/
void prim(int g[vertices][vertices])
{
/* create array of size equal to total number of vertices for storing the MST*/
int parent[vertices];
/* create k[vertices] array for selecting an edge having minimum weight*/
int k[vertices];
int mst[vertices];
int i, count,edge,v; /*Here 'v' is the vertex*/
for (i = 0; i < vertices; i++)
{
k[i] = INT_MAX;
mst[i] = 0;
}
k[0] = 0; /*It select as first vertex*/
parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/
for (count = 0; count < vertices-1; count++)
{
/*select the vertex having minimum key and that is not added in the MST yet from the set
of vertices*/
edge = minimum_key(k, mst);
mst[edge] = 1;
for (v = 0; v < vertices; v++)
{
if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])
{
parent[v] = edge, k[v] = g[edge][v];
}
}
}
/*Print the constructed Minimum spanning tree*/
printf("\n Edge \t Weight\n");
for (i = 1; i < vertices; i++)
printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);
}
int main()
{
int g[vertices][vertices] = {{0, 0, 3, 0, 0},
{0, 0, 10, 4, 0},
{3, 10, 0, 2, 6},
{0, 4, 2, 0, 1},
{0, 0, 6, 1, 0},
};
prim(g);
return 0;
}
RESULT
OUTPUT
Edge Weight
3 <-> 1 4
0 <-> 2 3
2 <-> 3 2
3 <-> 4 1
--------------------------------
Process exited after 1.827 seconds with return value 0
Press any key to continue . . .
AIM
ALGORITHM
A spanning tree is a sub-graph of an undirected connected graph, which includes all
the vertices of the graph with a minimum possible number of edges.
PROGRAM
#define MAX 30
edge_list elist;
int Graph[MAX][MAX], n;
edge_list spanlist;
void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
// Applying Krushkal Algo
void kruskalAlgo()
{
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;
{
if (Graph[i][j] != 0)
{
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}
sort();
spanlist.n = 0;
if (cno1 != cno2)
{
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
// Sorting algo
void sort()
{
int i, j;
edge temp;
int main()
{
int i, j, total_cost;
n = 6;
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;
Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;
kruskalAlgo();
print();
}
RESULT
OUTPUT
2-1:2
5-2:2
3-2:3
4-3:3
1-0:4
Spanning tree cost: 14
--------------------------------
Process exited after 1.867 seconds with return value 0
Press any key to continue . . .