Professional Documents
Culture Documents
DAA C Codes
DAA C Codes
1. Assignment 1 14-02-2020
2. Assignment 2 06-03-2020
3. Assignment 3 20-03-2020
4. Assignment 4 26-03-2020
5. Assignment 5 27-03-2020
6. Assignment 6 03-04-2020
7. Assignment 7 14-04-2020
8. Assignment 8 21-04-2020
9. Assignment 9 28-04-2020
Assignment Week
List of Experiments
No. No.
Assignment 1 I) Implement Binary Search using Divide and Conquer approach.
II) Implement Merge Sort, Quick Sort and Heap Sort using Divide and Conquer Week 1
approach.
Assignment 2 I) Find Maximum and Minimum element from a array of integer using Divide
and Conquer approach as well as dynamic programming approach.
II) WAP to multiply two 2x2 matrices using Strassen’s Matrix Multiplication.
The first matrix is
5 6
1 7
The second matrix is
6 2 Week 2
8 7
III) WAP to multiply two 4x4 matrices using Strassen's Matrix Multiplication.
Assignment 3 Find the minimum number of scalar multiplications needed for a chain of
matrices whose sequences are <5, 10, 3, 12, 5, 50, 6> using the dynamic
Week 3
programming technique.
Assignment 4 I) WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘1’, using the Dijkstra’s algorithm, using the
dynamic programming technique.
Week 4
Assignment 5 I) WAP to find out the all-pair-shortest-path for the given graph using the
Floyd-Warshall’s algorithm by the dynamic programming technique.
II) WAP using dynamic programming to find the optimal route for the given
graph using TSP and taking vertex ‘1’ as source.
Week 5
Assignment 6 I) WAP to implement BFS on the given graph starting at ‘a’. Week 6
Assignment 7 I) WAP using greedy method to find the MST for the given graph using the
Prim’s Algorithm.
II) WAP using greedy method to find the MST for the given graph using the Week 7
Kruskal’s Algorithm.
Assignment 8 I) Consider the following knapsack problem where n = 3, W = 20 Kgs, (v1, v2,
Week 8
v3) = (25, 24, 15), and (w1, w2, w3) = (18, 15, 10). WAP to find the optimal
II) Given a set of ‘10’ jobs with their si and fi, find the optimal sequence of
mutually compatible jobs using the greedy method: A = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10}, si = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12} and fi = {5, 7, 8, 10, 11, 12, 13, 14, 15,
16}.
Assignment 9 Write a procedure using B & B technique to solve the 15-puzzle problem.
(Take an initial state of your choice that will converge in the goal state.) Week 9
II) WAP using backtracking to find the chromatic number for the given
graph, using the graph-coloring problem.
Week
10
Assignment 11 The Maximum Sub-array Sum problem is to find the sub-array (A sub-array of
the array A [0…N-1] is A[i…j] where 0 ≤ i ≤ j < N ) for which the sum of its
elements is maximum. For example, given an array {12, -13, -5, 25, -20, 30,
10}, the maximum sub-array sum is 45 for sub-array {25, -20, 30, 10}. The
naive solution to this problem is to calculate the sum of all sub-arrays starting
with every element and returning the maximum of all. WAP to find the
maximum sub-array given below:
recursive call).
a recursive call).
Assignment 12 I) Find the only 10 digits number where the digit at the ith position (i = 0,
1, 2, 3 etc.) from left specifies the number of occurrences of digit "i" in
the given number.
II) Find the numbers from 1 to N that contains exactly k non-zero digits
Given two integers N and K. The task is to find the number of integers
between 1 and N (inclusive) that contains exactly K non-zero digits when
written in base ten.
Input: N = 25, K = 2
Output: 14
Explanation:
The digits with exactly 2 non zero digits between 1 and 25 are:
11, 12, 13, 14, 15, 16, 17,
18, 19, 21, 22, 23, 24, 25
ASSIGNMENT – 1
1.1. Implement Binary Search using Divide and Conquer approach.
Solution: FlowChart
Time Complexty:
For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation
Apply Masters Theorem for computing Run time complexity of recurrence relations
: T(N) = aT(N/b) + f(N)
Here, a = 1, b = 2 => log (a base b) = 1
also, here f(N) = n^c (log^k(n)) // k = 0 & c = log (a base b)
So, T(N) = O(N^c log^(k+1)N) = O(log(N)) // Average and worst case.
Best Case: O(1)
C code:
#include <stdio.h>
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main(void)
{
int i,n,temp = 0;
printf("Enter the no. of elements of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
if(arr[i] > arr[i+1])
{
temp = 1;
break;
}
}
if(temp == 1)
mergeSort(arr,0,n);
int x;
printf("enter the to be searched:\n");
scanf("%d",&x);
OUTPUT:
#RUN 1
#RUN 2
1.2. Implement Merge Sort, Quick Sort and Heap Sort using Divide and Conquer
approach.
Solution: FlowChart
Merge Sort:
Time Complexity:
C code:
#include<stdio.h>
#include<stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main()
{
int i,n;
printf("Enter the size of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
mergeSort(arr,0,n);
Quick Sort:
FlowChart:
Time Complexity:
Time taken by QuickSort in general can be written as following.
T(n) = T(k) + T(n-k-1) + (n)
The first two terms are for two recursive calls, the last term is for the partition
process. k is the number of elements which are smaller than pivot.
The time taken by QuickSort depends upon the input array and partition strategy.
Following are three cases.
Worst Case:
The worst case occurs when the partition process always picks greatest or
smallest element as pivot. If we consider above partition strategy where last
element is always picked as pivot, the worst case would occur when the array is
already sorted in increasing or decreasing order. Following is recurrence for worst
case.
T(n) = T(0) + T(n-1) + (n)
which is equivalent to
T(n) = T(n-1) + (n)
The solution of above recurrence is (n^2).
Best Case:
The best case occurs when the partition process always picks the middle element
as pivot. Following is recurrence for best case.
Average Case:
To do average case analysis, we need to consider all possible permutation of array
and calculate time taken by every permutation which doesn’t look easy.
We can get an idea of average case by considering the case when partition puts
O(n/9) elements in one set and O(9n/10) elements in other set. Following is
recurrence for this case.
C code:
#include<stdio.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int n;
printf("Enter the size of the Array:\n");
scanf("%d",&n);
int i,arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
quick_sort(arr,0,n-1);
for(i=0;i<n;i++)
printf("%d ",arr[i]);
return(0);
}
OUTPUT
Heap Sort:
Flowchart:
Time Complexity:
Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and
overall time complexity of Heap Sort is O(nLogn).
All three cases have same running time complexity.
C code:
#include<stdio.h>
#include<stdlib.h>
if (largest != i)
{
swap(&arr[i], &arr[largest]);
// Recursively heapify
heapify(arr, n, largest);
}
}
// call heapify
heapify(arr, i, 0);
}
int main()
{
int i,n;
printf("Enter the size of array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
heapSort(arr, n);
ASSIGNMENT – 2
2.1. Find Maximum and Minimum element from a array of integer using Divide and
Conquer approach as well as dynamic programming approach.
Solution: FlowChart
Time Complexity:
Form Algo: T(n) = 2.T(n/2) + 2
T(2) = 1
T(1) = 0
So, T(n) = 3*n / 2 – 2 = O(n)
If n is the power of 2, then algo needs O(n) comparisons, if not the comparasions
will be even more.
C code:
#include<stdio.h>
void maximum(int a[],int l,int h,int *min,int *max)
{
if(l==h)
{
if(*max<a[l])
*max=a[l];
if(*min>a[h])
*min=a[h];
return;
}
else if(l+1==h)
{
if(a[l]<a[h])
{
if(*min>a[l])
*min=a[l];
if(*max<a[h])
*max=a[h];
}
else
{
if(*min>a[h])
*min=a[h];
if(*max<a[l])
*max=a[l];
}
return;
}
int mid=(l+h)/2;
maximum(a,l,mid,min,max);
maximum(a,mid+1,h,min,max);
}
int main()
{
int n,max=-999999,min=999999;
int t=1,x;
while(t)
{
case 2:
max=a[0];
min=a[0];
for(i=1;i<n;i++)
{
max=max>a[i]?max:a[i];
min=min<a[i]?min:a[i];
}
printf("\nMaximum = %d\nMinimum = %d\n",max,min);
break;
case 3:
t=0;
}
}
OUTPUT:
2.2. WAP to multiply two 2x2 matrices using Strassen’s Matrix Multiplication.
The first matrix is
5 6
1 7
The second matrix is
6 2
8 7
Solution: Flowchart
Time Complexity:
As I mentioned above the Strassen’s algorithm is slightly faster than the general
matrix multiplication algorithm. The general algorithm’s time complexity is O(n^3),
while the Strassen’s algorithm is O(n^2.80).
You can see on the chart below how slightly faster is this even for large n.
Explanation:
Addition and Subtraction of two matrices takes O(N2) time. So time complexity can
be written as:
T(N) = 7T(N/2) + O(N^2)
From Master's Theorem, time complexity of above method is
O(N^Log7) which is approximately O(N^2.8074).
C code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[2][2], b[2][2], c[2][2], i, j;
int m1, m2, m3, m4, m5, m6, m7;
printf("Enter the elements of the first matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of the second matrix: \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The first Matrix is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
c[0][0] = m1 + m4 - m5 + m7;
c[0][1] = m3 + m5;
c[1][0] = m2 + m4;
c[1][1] = m1 - m2 + m3 + m6;
ASSIGNMENT 3
3. Find the minimum number of scalar multiplications needed for a chain of
matrices whose sequences are <5, 10, 3, 12, 5, 50, 6> using the dynamic
programming technique.
Solution: FlowChart
Time Complexity:
Implementation Rule:
Matrix-Chain(array p[1 .. n], int n) {
Array s[1 .. n − 1, 2 .. n];
FOR i = 1 TO n DO m[i, i] = 0; // initialize
FOR L = 2 TO n DO { // L=length of subchain
FOR i = 1 TO n − L + 1 do {
j = i + L − 1;
m[i, j] = infinity;
FOR k = i TO j − 1 DO { // check all splits
q = m[i, k] + m[k + 1, j] + p[i − 1] p[k] p[j];
IF (q < m[i, j]) {
m[i, j] = q;
s[i, j] = k;
}
}
}
}
return m[1, n](final cost) and s (splitting markers);
}
int A[n][n];
int i, j, k, L, q;
© Department of CSE Page 30 of 110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091
int main()
{
int n,i, result;
printf("Enetr the Size of the array:\n");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array:\n");
for ( i = 0; i < n; i++)
scanf("%d",&arr[i]);
ASSIGNMENT 4
4.1. WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘1’, using the Dijkstra’s algorithm, using the dynamic
programming technique.
Solution: FLOWCHART
Time Complexity:
This algo. Takes O(n2 ) in both Adj. list and adj Marix.
C code:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
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=1;
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 + 1,distance[i]);
printf("\nPath=%d",i + 1);
j=i;
do
{
j=pred[j];
printf("<-%d",j + 1);
}while(j!=startnode);
}
}
int main()
{
int G[MAX][MAX],i,j,V,u;
printf("Enter no. of vertices:");
scanf("%d",&V);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<V;i++)
for(j=0;j<V;j++)
scanf("%d",&G[i][j]);
return 0;
}
OUTPUT:
4.2. WAP using the single-source-shortest-path problem to find out the shortest
path from the source vertex ‘s’ using the Bellman-Ford’s algorithm, using the
dynamic programming technique.
Solution: FlowChart
Time Complexity:
Let: |V| = No. of Vertex
|E| = No of Edges
C code:
#include <stdio.h>
#include <stdlib.h>
#define max 20
#define infinity 9999
typedef struct
{
int e,v,array[max][max];
}graph;
for(i=1;i<=g.v;i++)
printf("vertex = %d,, Distance = %d \n",i,D[i]);
}
int main()
{
int u;
graph g;
printf("Enter the no. of vertex and edge of graph : ");
scanf("%d %d",&g.v,&g.e);
initialise(&g);
printf("Enter the starting vertex : ");
scanf("%d",&u);
bellman_ford(g,u);
return 0;
}
OUTPUT:
ASSIGNMENT – 5
5.1. WAP to find out the all-pair-shortest-path for the given graph using the Floyd-
Warshall’s algorithm by the dynamic programming technique.
Solution: FlowChart
Time Complxity:
Form the above Algorithm The Floyd-Warshall all-pairs shortest path runs in O(n3)
time, which is asymptotically no better than n calls to Dijkstra’s algorithm.
However, the loops are so tight and the program so short that it runs better in
practice.
C code:
#include<stdio.h>
#include<stdlib.h>
#define INF 99999
#define max 100
for(i=1;i<=g->E;i++)
{
scanf("%d %d %d",&u,&v,&w);
g->Adj[u][v]=w;
}
}
printf("\n");
}
printf("\n");
}
void floyd_warshall(graph g)
{
int i,j,k;
for(k=1;k<=g.V;k++)
{
for(i=1;i<=g.V;i++)
{
for(j=1;j<=g.V;j++)
g.Adj[i][j]=min(g.Adj[i][j],g.Adj[i][k]+g.Adj[k][j]);
}
int main()
{
graph G;
int i,j;
printf("Enter the number of vertices and edges:\n");
scanf("%d %d",&G.V,&G.E);
initialise_graph(&G);
floyd_warshall(G);
return 0;
}
OUTPUT:
5.2. WAP using dynamic programming to find the optimal route for the given graph
using TSP and taking vertex ‘1’ as source.
Solution: FlowChart
Time Complexity:
Recursive definition for travelling salesman problem can be written like this :-
• T(i,S) = min((i,j)+T(j,S-{j})) for all j belonging to S, when S is not equal to
NULL
• T(i,S) = (i,S) when S is equal to NULL.
There are n possible start vertices and 2n possible subgraphs. So this function will
be called on at most n⋅2n distinct arguments (the target never changes). Each call
performs at most O(n) work (there are at most n neighbors). Hence the total work
you're doing is O(n22n).
C code:
#include<stdio.h>
#define V 4
for(j=0;j<V;j++)
{
if((graph[i][j]<min)&& (visited[j]==0))
{
min=graph[i][j];
ctr=j;
}
}
visited[ctr]=1;
cost=cost+min;
}
return (cost+graph[ctr][0]);
}
int main()
{
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int visited[]={1,0,0,0};
int cost=travelling_sales_problem(graph,visited);
return 0;
}
OUTPUT:
ASSIGNMENT – 6
6.1. WAP to implement BFS on the given graph starting at ‘a’.
Solution: FlowChart
Time Complexity:
C code:
#include <stdio.h>
#include <stdlib.h>
#define err_code -999
#define max 20
typedef struct
{
int edge;
int vertex;
int Adj[20][20];
}graph;
q->array=(int *)malloc(sizeof(int)*num);
}
int is_full(queue q)
{
return((q.rear+1)%q.cap==q.front);
}
int is_empty(queue q)
{
return(q.front==-1);
}
int queue_size(queue q)
{
int data;
data=(q.cap-q.front+q.rear+1)%q.cap;
if(data==0)
return q.cap;
return data;
}
for(i=0;i<e;i++)
{
scanf("%c%c%c%c",&s,&u,&p,&v);
//printf("u=%d and v=%d",u-96,v-96);
g->Adj[u-96][v-96]=1;
g->Adj[v-96][u-96] = 1;
}
}
Enqueue(&q,j);
visited[j]=1;
}
}
}
}
int main()
{
int e,v;
char ch;
graph g;
printf("enter the number of vertices and the edges of graph : ");
scanf("%d %d",&v,&e);
printf("**All the inputs must be in lower case**\n");
initialise_graph(&g,v,e);
printf("\n");
printf("Enter the starting vertex:\n");
fflush(stdin);
scanf("%c",&ch);
int t = ch - 96;
bfs(&g,t,v);
}
OUTPUT:
Solution: FlowChart
Time Complexity:
The time complexity of DFS if the entire tree is traversed is O(V)O(V) where V is the
number of nodes. In the case of a graph, the time complexity is O(V + E)O(V+E)
where V is the number of vertexes and E is the number of edges.
C code:
#include<stdio.h>
#include<stdlib.h>
continue;
}
print_DFS(edges, n, i, visited);
}
}
}
graph *adj_mat(){
int i, u, v, sv;
char ch;
int* visited;
graph *G = (graph *)malloc(sizeof(graph));
printf("Enter the number of vertex and edge:\n");
scanf("%d %d",&G->V,&G->E);
G->Adj = (int **)malloc(sizeof(int) * (G->V ));
if(!(G->Adj))
{
printf("memory error\n");
return;
}
printf("\n");
return(G);
}
int main(){
graph *g;
int i,j;
g = (graph *)malloc(sizeof(graph));
g = adj_mat();
printf("\n\n");
printf("Crossponding Adj. Matrix:\n");
for(i = 0;i<g->V;i++)
{
for(j = 0;j<g->V;j++)
{
printf("%d ",g->Adj[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:
ASSIGNEMNT – 7
7.1. WAP using greedy method to find the MST for the given graph using the Prim’s
Algorithm.
Solution: Flowchart
Time Complexity:
Extracting the minimum and tracking the updated minimum edges (usually done
with a Heap(priority Queue), resulting in log(V) time complexity) occurs inside the
loop iterations
• the exact mechanisms involve end up needing to occur inside the inner loop
enough times that they are controlled by the time complexity of both loops.
Therefore, the complete time complexity for this phase of the algorithm is
O(2*E*log(V)). Dropping the constant yields O(E*log(V)).
C code:
#include <stdio.h>
#include <stdlib.h>
#define INF 999999
scanf("%d",&e);
printf("Enter 2 vertices and correspoding weight for each edge:\n");
setAdgecencyMatrix(adj, e ,v);
printAdjacencyMatrix(adj, v);
primMST(adj, v);
return 0;
}
OUTPUT:
7.2. WAP using greedy method to find the MST for the given graph using the
Kruskal’s Algorithm.
Solution: FlowChart
Time Complexity:
algorithm Kruskal(G) is
A := ∅
for each v ∈ G.V do
MAKE-SET(v)
for each (u, v) in G.E ordered by weight(u, v), increasing do
if FIND-SET(u) ≠ FIND-SET(v) then
A := A ∪ {(u, v)}
UNION(FIND-SET(u), FIND-SET(v))
return A
C code:
#include<stdio.h>
#include<stdlib.h>
}
}
}
int ctr = 0, j = 0;
tree cur_edge;
while (ctr != vertex - 1){
cur_edge = E[j];
//check if to add current edge in the output array is safe or not
int source_parent = find_parent(cur_edge.source, parent);
int dest_parent = find_parent(cur_edge.dest, parent);
if(source_parent != dest_parent){
output_edge[ctr] = cur_edge;
ctr++;
parent[source_parent] = dest_parent;
}
j++;
}
printf("\n");
printf("\n");
}
else
{
printf("%d-->%d : %d", output_edge[i].dest, output_edge[i].source, output_edge[i].weight);
printf("\n");
}
}
int sum = 0;
printf("The total cost is: ");
for(i = 0; i < vertex - 1 ; i++){
sum = sum + output_edge[i].weight;
}
printf("%d", sum);
}
int main()
{
int E, V;
printf("Enter the Number of Vertices and Edges:\n");
scanf("%d %d", &V, &E);
tree Edge[E];
int i, s, d, w;
printf("Enter the Source Vertix, Destination Vertex and Weight:\n");
for(i = 0; i< E; i++){
scanf("%d%d%d", &s, &d, &w);
Edge[i].source = s;
Edge[i].dest = d;
Edge[i].weight = w;
}
//printf("1\n");
Kruskals(Edge, E, V);
return 0;
}
OUTPUT:
ASSIGNEMENT – 8
8.1. Consider the following Knapsack problem where n = 3, W = 20 Kgs, (v1, v2, v3) =
(25, 24, 15), and (w1, w2, w3) = (18, 15, 10). WAP to find the optimal solution by
fractional knapsack (greedy method) as well as 0 / 1 knapsack (Dynamic
programming method).
Solution: FlowChart
Time Complexity:
In the fractional Knapsack problem: Main time is taking in sorting of the array, So
complexity depend on the type of sorting algorithm.
In case of Quick Sort: Best case O(n*log(n))
Worst case O(n2)
Average case O(n*log(n))
In 0/1 Knapsack Problem: Here the maximum of the empty set is taken to be zero.
Tabulating the results from m[0] up through m[W] gives the solution. Since the
calculation of each m[w] involves examining at most n items, and there are at most
W values of m[w] to calculate, the running time of the dynamic programming
solution is O(n*W).
C Code:
#include<stdio.h>
#include<stdlib.h>
}
}
return dp[n][max_weight];
}
}
double knapsack_greedy(sack1 *A, int n, int max_weight)
{
bsort(A, n);
int cur_weight = 0, i, reminder = 0;
double result = 0;
for(i = 0; i < n; i++){
if(cur_weight + A[i].weight <= max_weight){
cur_weight = cur_weight + A[i].weight;
result = result + A[i].profit;
}
else{
reminder = max_weight - cur_weight;
result = result + (A[i].profit * ((1.0) * reminder / A[i].weight));
break;
}
}
return result;
}
int main()
{
int swt;
printf("Enter 1 for greedy approach and 2 for DP approach for filling the sack:\n");
scanf("%d",&swt);
if(swt == 1){
int n, max_weight;
int p, w;
printf("Enter the number of objects and maximum weight that can be filled in the
sack:\n");
scanf("%d %d",&n, &max_weight);
int i;
sack1 A[n];
printf("Enter the profit value and wight value of the object:\n");
for(i = 0; i < n; i++){
scanf("%d %d",&p, &w);
A[i].profit = p;
A[i].weight = w;
A[i].probywgt = ((double)p / w);
}
double result;
result = knapsack_greedy(A, n, max_weight);
printf("The maximum profit by the given capacity of the sack is:\n");
printf("%lf", result);
}
else if(swt == 2){
int n, max_weight;
printf("Enter the number of objects and the maximum capacity of the sack:\n");
scanf("%d %d", &n, &max_weight);
sack2 A[n];
int i;
printf("Enter the profit and weight of the objects:\n");
for(i = 0; i < n; i++)
scanf("%d %d", &A[i].profit, &A[i].value);
int result;
result = knapsack_DP(A, n, max_weight);
printf("The maximum profit by the given capacity of the sack is:\n");
printf("%d", result);
}
else{
printf("Invalid input\n");
}
return 0;
}
OUTPUT:
8.2. Given a set of ‘10’ jobs with their si and fi, find the optimal sequence of mutually
compatible jobs using the greedy method: A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, si = {3, 4, 5,
6, 7, 8, 9, 10, 11, 12} and fi = {5, 7, 8, 10, 11, 12, 13, 14, 15, 16}.
Solution: Flowchart
Time Complexity:
When activities are sorted by their finish time: O(N)
When activities are not sorted by their finish time, the time complexity is O(N log N)
due to complexity of sorting.
C code:
#include<stdio.h>
#include<stdlib.h>
int ctr = 1;
printf("\n");
for(i = 1; i < n ; i ++){
if(output[i] != 0){
printf("%d --> %d", A[i].start, A[i].finish);
printf("\n");
ctr++;
}
}
printf("Total number of activity is: %d", ctr);
}
int main()
{
int n, i;
printf("Enter the number of activity a person want to perform:\n");
scanf("%d",&n);
act A[n];
printf("Enter the starting time and finishing time:\n");
for(i = 0; i< n; i++)
scanf("%d %d", &A[i].start, &A[i].finish);
Activity(A, n);
}
OUTPUT:
ASSIGNMENT – 9
9. Write a procedure using B & B technique to solve the 15-puzzle problem. (Take
an initial state of your choice that will converge in the goal state.)
Solution: FlowChart
Time Complexity:
The time complexity of the algo. basically, depends on exploring a live node,
computing cost of construction for each child, finding next E-node. Since, the Algo
is based on B-search. B-search always finds a goal state nearest to root node.
Whatever may be the initial arrangement, the algo always attempts to make the
same sequence of legal moves. The B-search always generate state space tree
level wise. Therefore, the time complexity of this Algo. i.e. => O(|V| + |E|).
C Code:
#include<stdio.h>
#include<conio.h>
int m=0,n=4;
void main()
{
int p,i,j,n=4,a[10][10],t[10][10],temp[10][10],r[10][10];
int m=0,x=0,y=0,d=1000,dmin=0,l=0;
printf("\nEnter the matrix to be solved,space with zero :\n");
for(i=0;i < n;i++)
for(j=0;j < n;j++)
scanf("%d",&a[i][j]);
while(!(check(a,t)))
{
l++;
d=1000;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
if(a[i][j]==0)
{
x=i;
y=j;
}
}
if(x!=0)
{
p=temp[x][y];
temp[x][y]=temp[x-1][y];
temp[x-1][y]=p;
}
m=cal(temp,t);
dmin=l+m;
if(dmin < d)
{
d=dmin;
for(i=0;i < n;i++)
for(j=0;j < n;j++)
r[i][j]=temp[i][j];
}
OUTPUT:
ASSIGNMENT – 10
10.1. WAP to implement the 8-Queen’s problem using the method of backtracking.
Solution: Flowchart
Time Complexity:
In the function: is_safe, it iterates over n => O(n2)
In function solve N-queen: In each iteration, there is call of is safe function which of
given order and a recursive call with smaller argument is done:
Therefore, T(n) = n.T(n – 1) + O(n2)
C code:
#include<stdio.h>
#include<stdlib.h>
#define true 1
#define false 0
int n;
int **board;
}queen;
int r;
if(a->board[r][i] == 1){
return false;
digL = start;
digR = i;
if(a->board[digL][digR] == 1){
return false;
digR--;
digL--;
digL = start;
digR = i;
if(a->board[digL][digR] == 1){
return false;
digR++;
digL--;
return true;
//base case
if(a->n == start){
//print board
int x, y;
printf("+-");
printf("-");
printf("+");
printf("\n");
printf("| ");
if(a->board[x][y] == 1){
printf("Q ");
else{
printf(". ");
printf("|");
printf("\n");
printf("+-");
printf("-");
printf("+");
printf("\n\n");
return false;
int i;
a->board[start][i] = 1;
int placeNext;
if(placeNext){
return true;
a->board[start][i] = 0;
return false;
int main()
scanf("%d",&a->n);
int i, j;
solveNqueen(a, 0);
return 0;
OUTPUT:
10.2. WAP using backtracking to find the chromatic number for the given graph, using the graph-
coloring problem.
Solution:
FlowChart
Time Complexity:
Time Complexity will depend on no. of colors(c) and vertices(v). Total possible
arrangements for
C colours and v vertices is Cn
So running time will be O(Cn).
C code:
#include<stdio.h>
#include<stdlib.h>
if(!(G->Adj)){
printf("memory error\n");
return 0;
}
for(i = 0;i<G->V; i++)
G->Adj[i] = (int *)malloc(sizeof(int) * (G->V));
}
return(G);
}
int checkForValidation(graph *g)
{
int i,j;
for(i = 0; i < g->V; i++){
for(j = i + 1; j < g->V; j++){
if(g->Adj[i][j] == 1 && g->color[j] == g->color[i])
return 0;
}
}
return 1;
}
int graphColoring(graph *g, int start)
{
if(start == g->V){
if(checkForValidation(g)){
int i;
printf("Solution for the given graph is::\n");
for(i = 0; i < g->V; i++){
printf("Vertex::%d --> ",i + 1);
printf("%d",g->color[i]);
printf("\n");
}
return 1;
}
return 0;
}
int i;
for(i = 1; i <= g->m; i++){
g->color[start] = i;
if(graphColoring(g, start + 1)){
return 1;
}
g->color[start] = 0;
}
return 0;
}
int main(){
graph *g;
int i,j;
g = (graph *)malloc(sizeof(graph));
g = adj_mat();
g->color = (int *)malloc(sizeof(int) * g->V);
for(i = 0; i < g->V; i++)
g->color[i] = 0;
printf("\n\n");
int start;
printf("Enetr the starting vertex:: ");
scanf("%d",&start);
graphColoring(g, start - 1);
return 0;
}
OUTPUT:
ASSIGNMENT – 11
11. The Maximum Sub-array Sum problem is to find the sub-array (A sub-array of
the array A [0…N-1] is A[i…j] where 0 ≤ i ≤ j < N ) for which the sum of its elements is
maximum. For example, given an array {12, -13, -5, 25, -20, 30, 10}, the maximum
sub-array sum is 45 for sub-array {25, -20, 30, 10}. The naive solution to this
problem is to calculate the sum of all sub-arrays starting with every element and
returning the maximum of all. WAP to find the maximum sub-array given below:
(1) Divide the given array in two halves.
(2) Return the maximum of the following:
i. Maximum sub-array sum in the left half (Make a
recursive call).
ii. Maximum sub-array sum in the right half (Make
a recursive call).
Solution: Flowchart
Time Complexity:
maxSubArraySum() is a recursive method and time complexity can be expressed
as following recurrence relation.
T(n) = 2T(n/2) + Θ(n)
The above recurrence is similar to Merge Sort and can be solved either using
Recurrence Tree method or Master method. It falls in case II of Master Method and
solution of the recurrence is Θ(nLogn).
C code:
#include<stdio.h>
#include<stdlib.h>
//
int left_rec = INT_MIN, right_rec = INT_MIN, sum = 0, i;
//We will get the maximum of the left or right Sum Subarray
int maxSum = max(left_MSS, right_MSS);
//return the maximum of the left or right or best subarray throught the middle
return(max(maxSum, left_rec + right_rec));
}
int main()
{
int n;
printf("Array Size:\n");
scanf("%d",&n);
int arr[n];
printf("Enter array values:\n");
int i, a;
for(i = 0; i < n; i++){
scanf("%d",&a);
arr[i] = a;
}
int result = solve(arr, n);
printf("Maximum Sub_Array Sum is: %d\n",result);
return 0;
}
OUTPUT:
ASSIGNMENT – 12
12.1. Find the only 10 digit number where the digit at the ith position (i = 0, 1, 2, 3 etc.)
from left specifies the number of occurrences of digit "i" in the given number.
Solution: FlowChart
Time Complexity:
C code:
#include<stdio.h>
#include<stdlib.h>
void solve(int n)
{
if(n == 1 || n == 2 || n == 3 || n == 6){
printf("No such number exists for %d digit number\n", n);
return;
}
else if(n == 4){
printf("The required number is: 1210 or 2020");
return;
}
else if(n == 5){
printf("The required number is: 21200");
}
else{
int arr[n];
arr[0] = n - 4;
arr[1] = 2;
arr[2] = 1;
int i = n - 7;
int x = 3;
while(i > 0){
arr[x] = 0;
i -= 1;
x += 1;
}
for(i = n - 1; i >= n - 4; i--){
arr[i] = 0;
if(i == n - 4)
arr[i] = 1;
}
printf("The required number is:\n");
for(i = 0; i < n; i++){
printf("%d",arr[i]);
}
return;
}
}
int main()
{
int num;
printf("Enter the number of digits:\n");
scanf("%d",&num);
solve(num);
return 0;
}
OUTPUT:
12.2. From this graph find the MST by using 1> Prims Algorithm 2>Kruskal's Algorithm.
Prim’s Algorithm
Solution: Flowchart
Time Complexity:
Extracting the minimum and tracking the updated minimum edges (usually done with a Heap(priority Queue),
resulting in log(V) time complexity) occurs inside the loop iterations
the exact mechanisms involve end up needing to occur inside the inner loop enough times that they are
controlled by the time complexity of both loops. Therefore, the complete time complexity for this phase of the
algorithm is O(2*E*log(V)). Dropping the constant yields O(E*log(V)).
C code:
#include <stdio.h>
#include <stdlib.h>
#define INFINITY 999999
int minKey(int key[], int mstSet[], int V) {
int min = INFINITY, min_index, v;
for (v = 0; v < V; v++)
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
int printMST(int parent[], int **graph, int V) {
int cost = 0, i;
printf("Edge \tWeight\n");
for (i = 1; i < V; i++) {
printf("%d--%d \t%d\n", parent[i], i, graph[i][parent[i]]);
cost += graph[i][parent[i]];
}
printf("Cost: %d.\n", cost);
}
void primMST(int **graph, int V) {
int parent[V];
int key[V];
int mstSet[V];
int i, count, u, v;
for (i = 0; i < V; i++)
key[i] = INFINITY, mstSet[i] = 0;
key[0] = 0;
parent[0] = -1;
for (count = 0; count < V - 1; count++) {
u = minKey(key, mstSet,V);
mstSet[u] = 1;
for (v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph, V);
}
© Department of CSE Page 102 of
110
Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata- 700091
int main()
{
int **adj,i,j,v ,e, bi;
printf("Number of vertices: ");
scanf("%d",&v);
adj = (int **)malloc(sizeof(int*)*v);
for(i = 0; i < v; i++){
adj[i] = (int *)malloc(sizeof(int)*v);
for(j = 0; j < v; j++){
if(i==j)
adj[i][j] = 0;
else
adj[i][j] = INFINITY;
}
}
printf("Number of edges: ");
scanf("%d",&e);
printf("Enter 0 if graph is Directed, else enter 1: ");
scanf("%d", &bi);
printf("Enter 2 vertices and correspoding weight for each edge:\n");
setAdgecencyMatrix(adj, e ,v, bi);
printAdjacencyMatrix(adj, v);
primMST(adj, v);
return 0;
}
OUTPUT:
Kruskal’s Algorithm.
Solution: FlowChart
Time Complexity:
algorithm Kruskal(G) is
A := ∅
for each v ∈ G.V do
MAKE-SET(v)
for each (u, v) in G.E ordered by weight(u, v), increasing do
if FIND-SET(u) ≠ FIND-SET(v) then
A := A ∪ {(u, v)}
UNION(FIND-SET(u), FIND-SET(v))
return A
C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Edge {
int u, v, weight;
};
struct Graph {
int V, E;
struct Edge* edge;
};
struct subset {
int parent;
int rank;
};
x = find(subsets, next_edge.u);
y = find(subsets, next_edge.v);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
printMST(result,e);
return;
}
int main()
{
int V, E;
printf("Number of vertices: ");
scanf("%d",&V);
printf("Number of edges: ");
scanf("%d",&E);
struct Graph* graph = createGraph(V, E);
int i;
printf("Enter 2 vertices and correspoding weight for each edge:\n");
for(i = 0; i<E; i++)
scanf("%d %d %d", &graph->edge[i].u, &graph->edge[i].v, &graph->edge[i].weight);
KruskalMST(graph);
return 0;
}
OUTPUT:
12.3. Show how to multiply the complex numbers a+bi and c+di (i is the imaginary number √(-1) using
only three multiplications of real numbers. Your code should take a,b,c and d as input and produce
the real component ac-bd and the imaginary component ad+bc separately.
Solution: FlowChart
Time Complexity:
C Code:
#include <stdio.h>
int main(){
int a,b,c,d,x,y,z;
printf("Enter the values of a, b, c & d: ");
scanf("%d%d%d%d", &a, &b, &c, &d);
x = a*c;
y = b*d;
z = (a+b)*(c+d);
printf("The product is: %d%+di.\n", (x-y),(z-x-y));
}
Output: