Design and Analysis of Algorithm Laboratory
Design and Analysis of Algorithm Laboratory
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 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 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;
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;
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;
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 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;
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.
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;
scanf("%d",&n);
printf("Enter the weights of each item:");
for(i=0;i<n;i++)
{
scanf("%d",&weights[i]);
}
int maximum=knapsack(weights,values,n,capacity);
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");
u = find(u);
v = find(v);
if (uni(u, v))
{
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
mincost += min;
}
int find(int i)
{
while (parent[i])
i = parent[i];
return i;
}
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();
scanf("%d",&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)
mincost+=min;
visited[b]=1;
cost[a][b]=cost[b][a]=999;
// getch();
}
8. Write C/C++ programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
#include <stdio.h>
#include <limits.h>
int main()
{
int V; // Number of vertices in the graph
int i, j;
int graph[MAX_VERTICES][MAX_VERTICES];
return 0;
}
#include <stdio.h>
#include <limits.h>
#define MAX_N 10
if (memo[current][visited] != -1) {
return memo[current][visited];
}
parent[current][visited] = next_city;
return memo[current][visited] = min_cost;
}
int main() {
printf("Enter the number of cities: ");
scanf("%d", &n);
printf("Optimal path:\n");
printPath(0); // Print path starting from city 0
return 0;
}
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
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];
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;
}
int main() {
int V; // Number of vertices in the graph
int i, j;
int graph[MAX][MAX];
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]);
}
}
}
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);
}