Design and Analysis of Algorithm Laboratory

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Design and analysis of algorithm laboratory

1 Write C/C++ programs to perform Linear and Binary search of an element from a set
of n elements. Run the program for varied values of n> 5000 and record the time
taken to sort. Plot a graph of the time taken versus non graph sheet. The elements can
be read from a file or can be generated using the random number generator.
Demonstrate using C/C++ how the divide-and-conquer method works along with its
time complexity analysis: worst case, average case and best case. Compare the
performance of both the algorithms.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int i,j,k,ch,n,key,temp;
int linearsearch(int a[],int key,int n)
{
for(i=0;i<n;i++)
{
if(a[i]==key)
{
return 0;
}
}
return -1;
}

int binarysearch(int a[],int key,int n)


{
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

int low=0,mid,high=n-1;

while(low<=high)
{
mid=(low+high)/2;

if(a[mid]==key)
return 0;
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}

int randomarray(int a[],int n)


{
srand(time(NULL));

int main()
{
int a[100000],i,j,k,p,q,key;
clock_t start,end;
double time;

FILE *fp1,*fp2;

fp1=fopen("linearsearch.txt","w");
fp2=fopen("binarysearch.txt","w");
for(;;)
{
printf("1.linaersearch 2.binarysearch 3.exit");
printf("enter the choice");
scanf("%d",&ch);

switch(ch)
{
case 1:

for(k=0;k<10;k++)
{
n=5000;
for(i=0;i<n;i++)
{
a[i]=rand()%10000;
}
key=rand()%10000;

start=clock();
p=linearsearch(a,key,n);
if(p==0)
printf("\nfound");
else
printf("\nnot found");
end=clock();

time=((double)(end-start))/CLOCKS_PER_SEC;

printf("\n time taken %lf",time);


fprintf(fp1,"%d\t%lf\n",n,time);
n+=500;
}
fclose(fp1);
//free(n);
break;
case 2:
n=5000;
for(k=0;k<10;k++)
{
for(i=0;i<n;i++)
a[i]=rand()%10000;
key=rand()%10000;

start=clock();
q=binarysearch(a,key,n);
if(q==0)
printf("\nfound");
else
printf("\nnot found");
end=clock();

time=((double)(end-start))/CLOCKS_PER_SEC;

printf("\n time taken %lf",time);


fprintf(fp2,"%d\t%lf\n",n,time);
n+=500;
}
fclose(fp2);
//free(n);
break;

case 3:exit(0);
}
}
}
2 Write C/C++ programs to 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. Plot a graph of the time taken versus non
graph sheet. The elements can be read from a file or can be generated using the
random number generator. Demonstrate using C/C++ how the divide-and-conquer
method works along with its time complexity analysis: worst case, average case and
best case.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int first,last,n,a[10000],i,j,k;

int quicksort(int a[],int first,int last)


{
int i,pivot,temp;

if(first<last)
{
pivot=first;
i=first;
j=last;

while(i<j)
{
while(a[i]<a[pivot] && i<last)
i++;
while(a[j]>a[pivot])
j--;

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

temp=a[pivot];
a[pivot]=a[j];
a[j]=temp
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}

int randomarray(int a[],int n)


{
srand(time(NULL));
for(i=0;i<n;i++)
{
a[i]=rand()%10000;
}
}

int main()
{
clock_t start,end;
double time_taken;
n=5000;

FILE *fp1;
fp1=fopen("quicksort1.txt3","w");

for(k=0;k<10;k++)
{
randomarray(a,n);
start=clock();
quicksort(a,first,last);
end=clock();
time_taken=((double)(end-start))/CLOCKS_PER_SEC;
printf("the time taken for %6f",time_taken);
fprintf(fp1,"%d\t %6f\n",n,time_taken);
n+=500;

}
fclose(fp1);

}
Write C/C++ programs to 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. Plot a graph of the time taken versus non
graph sheet. The elements can be read from a file or can be generated using the
random number generator. Demonstrate using C/C++ how the divide-and-conquer
method works along with its time complexity analysis: worst case, average case and
3. best case.
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int i,k;
// Function to merge the two halves of the array in sorted order
void merge(int arr[], int left[], int leftSize, int right[], int rightSize)
{
int i = 0, j = 0, k = 0;

while (i < leftSize && j < rightSize)


{
if (left[i] <= right[j])
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}

while (i < leftSize)


{
arr[k] = left[i];
i++;
k++;
}

while (j < rightSize)


{
arr[k] = right[j];
j++;
k++;
}
}

// Recursive function to perform merge sort


void mergeSort(int arr[], int size) {
if (size < 2)
return;

int mid = size / 2;


int left[mid];
int right[size - mid];

for (int i = 0; i < mid; i++)


left[i] = arr[i];

for (int i = mid; i < size; i++)


right[i - mid] = arr[i];

mergeSort(left, mid);
mergeSort(right, size - mid);
merge(arr, left, mid, right, size - mid);
}
int main()
{
int arr[10000];
int size=5000;
clock_t start,end;
double time_taken;

FILE *fp1;
fp1=fopen("mergesort.txt","w");

for(k=0;k<10;k++)
{
for(i=0;i<size;i++)
{
arr[i]=rand()%10000;
}
start=clock();
mergeSort(arr, size);

end=clock();
time_taken=((double)(end-start))/CLOCKS_PER_SEC;
printf("the time taken for size of %d\t to sort array is %lf\n",size,time_taken);
fprintf(fp1,"%d\t %lf\n",size,time_taken);

size+=500;
}
fclose(fp1);

return 0;
}
x

Implement in C/C++, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.

(a) Dynamic Programming method


#include<stdio.h>
#include<stdlib.h>
#define m 6

int max(int a,int b)


{
return (a>b) ? a:b;
}

void print(int dptable[m][m],int n,int capacity)


{
int i,w;
for(i=0;i<=n;i++)
{
for(w=0;w<=capacity;w++)
{
printf("%d\t",dptable[i][w]);
}
printf("\n");
}
}
4.

int knapsack(int weights[m],int values[m],int n,int capacity)


{
int i,w,dptable[n+1][capacity+1];

for(i=0;i<=n;i++)
{
for(w=0;w<=capacity;w++)
{
if(i==0 || w==0)
dptable[i][w]=0;

else if(weights[i-1]<=w)
dptable[i][w]=max(values[i-1]+dptable[i-1][w-weights[i-
1]],dptable[i-1][w]);

else
dptable[i][w]=dptable[i-1][w];
}
}

print(dptable,n,capacity);

return (dptable[n][capacity]);
}

int main()
{
int i,n,weights[m],values[m],capacity;

printf("Enter the numebr of items:");

scanf("%d",&n);
printf("Enter the weights of each item:");
for(i=0;i<n;i++)
{
scanf("%d",&weights[i]);
}

printf("Enter the values of each items:");


for(i=0;i<n;i++)
{
scanf("%d",&values[i]);
}

printf("Enter the capacity of kanpsack:");


scanf("%d",&capacity);

int maximum=knapsack(weights,values,n,capacity);

printf("Maximum value is :%d\n",maximum);


return 0;
}

(b) Greedy method


#include<stdio.h>
#include<stdlib.h>
void knapsack(int n,float weight[],float profit[],float capacity)
{
float x[20],tp=0;
int u,i,j;
u=capacity;
for(i=0;i<n;i++)
x[i]=0.0;
for(i=0;i<n;i++)
{
if(weight[i]>u)
break;
else
{
x[i]=1.0;
tp=tp+profit[i];
u=u-weight[i];
}
}
if(i<n)
x[i]=u/weight[i];
tp=tp+(x[i]*profit[i]);
printf("the resultant vector is ");
for(i=0;i<n;i++)
printf("%f\t",x[i]);
printf("the total profit is %f",tp);
}
void main()
{
float weight[20],profit[20],capacity;
int num,i,j;
float ratio[20],temp;
printf("enter the number of objects");
scanf("%d",&num);
printf("enter the weight and profit of each object");
for(i=0;i<num;i++)
scanf("%f%f",&weight[i],&profit[i]);
printf("enter the capacity");
scanf("%f",&capacity);
for(i=0;i<num;i++)
{
ratio[i]=profit[i]/weight[i];
}
for(i=0;i<num;i++)
{
for(j=i+1;j<num;j++)
{
if(ratio[i]<ratio[j])
{
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;

temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;

temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
}
}
knapsack(num,weight,profit,capacity);
}

5. From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm. Write the program in C/C++.

#include<stdio.h>
#define INF 9999
#define MAX 10
void dijkstra (int G[MAX][MAX], int n, int stnode)
{
int cost[MAX][MAX], dis[MAX], pred[MAX];
int vis[MAX] = {0}, count, mindist, nextnode, i,j;
for(i=0; i<n; i++)
for(j=0; j<n; j++)
cost[i][j] = G[i][j] ? G[i][j] : INF;
for(i=0; i<n; i++)
{
dis[i] = cost[stnode][i];
pred[i] = stnode;
}
dis[stnode] = 0;
vis[stnode] = 1;
count = 1;

while(count < n)
{
mindist = INF;
for(i=0; i<n; i++)
if(dis[i] < mindist && !vis[i])
{
mindist = dis[i];
nextnode = i;
}
vis[nextnode] = 1;
for(i=0; i<n; i++)
if (!vis[i])
if(mindist + cost[nextnode][i] < dis[i])
{
dis[i] = mindist + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}
for(i=0; i<n; i++)
{
if(i != stnode)
{
printf("\n Distance of the Node %d = %d", i,dis[i]);
printf("\nPath = %d", stnode);
int temp[MAX];
int temp_count = 0;
j = i;
do {
temp[temp_count++] = j;
j = pred[j];
} while (j != stnode);
for(j = temp_count - 1; j>=0; j--)
printf(" -> %d", temp[j]);
} printf("\n");
}
}

int main()
{
int G[MAX][MAX], i, j, n ,u;
printf("\nEnter the Number of Vertices: ");
scanf("%d", &n);
printf("\nEnter the Adjacency Matrix: \n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &G[i][j]);
printf("\nEnter the Starting Node: \n");
scanf("%d", &u);
dijkstra(G, n, u);
return 0;
}
6. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal's algorithm. Use Union-Find algorithms in your program. Write the program
in C/C++.
#include <stdio.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;
}

7. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm. Write the program in C/C++.
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];

void main()

// clrscr();

printf("\nEnter the number of nodes:");

scanf("%d",&n);

printf("\nEnter the 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;

visited[1]=1;

printf("\n");

while(ne < n)

for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)

if(cost[i][j]< min)

if(visited[i]!=0)

min=cost[i][j];

a=u=i;

b=v=j;

if(visited[u]==0 || visited[v]==0)

printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);

mincost+=min;

visited[b]=1;

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

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

// getch();

}
8. Write C/C++ programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
#include <stdio.h>
#include <limits.h>

#define MAX_VERTICES 100


#define INF 999

void floyd(int graph[][MAX_VERTICES], int V)


{
int dist[MAX_VERTICES][MAX_VERTICES];

// Initialize the distance matrix with the input graph


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}

for (int k = 0; k < V; k++) {


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {

if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] <


dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

printf("Shortest Path Matrix:\n");


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF) {
printf("INF\t");
} else {
printf("%d\t", dist[i][j]);
}
}
printf("\n");
}
}

int main()
{
int V; // Number of vertices in the graph
int i, j;
int graph[MAX_VERTICES][MAX_VERTICES];

printf("Enter the number of vertices in the graph: ");


scanf("%d", &V);

printf("Enter the adjacency matrix representing the graph (use %d for no


edge):\n", INF);
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
floyd(graph, V);

return 0;
}

(b) Implement Travelling Sales Person problem using Dynamic programming

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

#define MAX_N 10

int n; // Number of cities


int dist[MAX_N][MAX_N]; // Distance matrix
int memo[MAX_N][1 << MAX_N]; // Memoization table
int parent[MAX_N][1 << MAX_N]; // Parent information for constructing the
path

int tsp(int current, int visited) {


if (visited == (1 << n) - 1) { // All cities visited
return dist[current][0];
}

if (memo[current][visited] != -1) {
return memo[current][visited];
}

int min_cost = INT_MAX;


int next_city = -1;
for (int i = 0; i < n; i++) {
if (!(visited & (1 << i))) { // City i not visited
int new_cost = dist[current][i] + tsp(i, visited | (1 << i));
if (new_cost < min_cost) {
min_cost = new_cost;
next_city = i;
}
}
}

parent[current][visited] = next_city;
return memo[current][visited] = min_cost;
}

void printPath(int start) {


int current = start;
int visited = 1 << start;
printf("Path: %d", current+1);

while (visited != (1 << n) - 1) {


int next_city = parent[current][visited];
printf(" -> %d", next_city+1);
visited |= (1 << next_city);
current = next_city;
}

printf(" -> %d\n", start+1);


}

int main() {
printf("Enter the number of cities: ");
scanf("%d", &n);

printf("Enter the distance matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &dist[i][j]);
}
}

for (int i = 0; i < n; i++) {


for (int j = 0; j < (1 << n); j++) {
memo[i][j] = -1;
}
}

int min_path = tsp(0, 1); // Start from city 0


printf("Minimum path cost: %d\n", min_path);

printf("Optimal path:\n");
printPath(0); // Print path starting from city 0

return 0;
}

9. Implement the C/C++ programs to:


a) Obtain the Topological ordering of vertices in a given digraph.
#include <stdio.h>

int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;

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


scanf("%d",&n);

printf("Enter the adjacency matrix:\n");


for(i=0;i<n;i++)
{
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}

for(i=0;i<n;i++)
{
indeg[i]=0;
flag[i]=0;
}

for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];

printf("\nThe topological order is:");

while(count<n)
{
for(k=0;k<n;k++)
{
if((indeg[k]==0) && (flag[k]==0))
{
printf("%d ",(k+1));
flag [k]=1;
}

for(i=0;i<n;i++)
{
if(a[i][k]==1)
indeg[k]--;
}
}

count++;
}
return 0;
}

b) Compute the transitive closure of a given directed graph using Warshall’s


Algorithm
#include <stdio.h>

#define MAX 100

void warshall(int graph[][MAX], int V) {


int transClosure[MAX][MAX];

// Initialize the transitive closure matrix with the input graph


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
transClosure[i][j] = graph[i][j];
}
}

// Compute the transitive closure using Warshall's algorithm


for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
// If vertex k is an intermediate vertex on the path from i to j,
// and there is a path from i to k and k to j, then update the closure.
if (transClosure[i][k] && transClosure[k][j]) {
transClosure[i][j] = 1;
}
}
}
}

// Print the transitive closure matrix


printf("Transitive Closure Matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", transClosure[i][j]);
}
printf("\n");
}
}

int main() {
int V; // Number of vertices in the graph
int i, j;
int graph[MAX][MAX];

printf("Enter the number of vertices in the graph: ");


scanf("%d", &V);

printf("Enter the adjacency matrix representing the graph (0/1):\n");


for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}

warshall(graph, V);

return 0;
}

10 Design and implement in C/C++ to find a subset of a given set S = {Sl, S2.. Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S
= {1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a
suitable message, if the given problem instance doesn't have a solution.

#include<stdio.h>
#define TRUE 1
#define FALSE 0
int inc[50],w[50],sum,n;
int promising(int i,int wt,int total);
void sumset(int i,int wt,int total)
{
int j;
if(promising(i,wt,total)) {
if(wt==sum) {
printf("\n{\t");
for (j=0;j<=i;j++)
if(inc[j])
printf("%d\t",w[j]);
printf("}\n");
} else {
inc[i+1]=TRUE;
sumset(i+1,wt+w[i+1],total-w[i+1]);
inc[i+1]=FALSE;
sumset(i+1,wt,total-w[i+1]);
}
}
}

int promising(int i,int wt,int total) {


return(((wt+total)>=sum)&&((wt==sum)||(wt+w[i+1]<=sum)));
}

void main() {
int i,j,n,temp,total=0;
printf("\n Enter how many numbers:\n");
scanf("%d",&n);
printf("\n Enter %d numbers to the set:\n",n);
for (i=0;i<n;i++) {
scanf("%d",&w[i]);
total+=w[i];
}
printf("\n Input the sum value to create sub set:\n");
scanf("%d",&sum);
for (i=0;i<=n;i++)
for (j=0;j<n-1;j++)
if(w[j]>w[j+1]) {
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
printf("\n The given %d numbers in ascending order:\n",n);
for (i=0;i<n;i++)
printf("%d \t",w[i]);
if((total<sum))
printf("\n Subset construction is not possible"); else {
for (i=0;i<n;i++)
inc[i]=0;
printf("\n The solution using backtracking is:\n");
sumset(-1,0,total);
}

You might also like