Professional Documents
Culture Documents
Ada1 10
Ada1 10
1. Implement Recursive Binary search and Linear search and determine the time required
to search an element. Repeat the experiment for different values of n, the number of
elements in the list to be searched and plot a graph of the time taken versus n.
Algorithm:
Algorithm linearsearch(a,l,n,x)
// input : a[l:n] of sorted elements, x=> search key
For i->0 to n-1
if(a[i]=x)
return i
end if
end for
return -1
Program
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<time.h>
int linsearch(int [],int,int);
int binsearch(int [],int,int,int);
void genrand(int [],int);
void disp(int [],int);
void sort(int [],int);
int main(void)
{
int arr[500],n,key,i,pos=0,ch;
struct timeval tv;
double st,end;
system("clear");
do
{
printf("\n1. Linear Search");
printf("\n2. Binary Search");
printf("\n3. Exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
OUTPUT
2. Sort a given set of elements using the Insertion Sort method and determine the time
required to sort the elements. Repeat the experiment for different values of n, the number of
elements in the list to be sorted and plot a graph of the time taken versus n.
Program
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
OUTPUT
Enter number of terms(should be less than 100): 5
Enter elements: 12
1
2
5
3
In ascending order: 1 2 3 5 12
Algorithm Merge_Sort(A,low,high)
//given an array A of size n (high-low+1). This algorithm sorts elements in ascending order.
// the variables low and high are used to identify the position of first and last element in each
partition.
Step1: if(low<high)
Step2: mid=(low+high)/2
Step3: call Merge_Sort(A,low,mid)
Step4: call Merge_Sort(A,mid+1,high)
Step5: call Merge(A,low,mid,high)
[end if]
Step 6: exit
Program
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
void fnGenRandInput(int [], int);
void fnDispArray( int [], int);
void fnMerge(int [], int ,int ,int);
void fnMergeSort(int [], int , int);
int main()
{
struct timeval tv;
double dStart,dEnd;
int iaArr[100], iNum;
system("clear");
printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(iaArr,iNum);
fnDispArray(iaArr,iNum);
gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);
fnMergeSort(iaArr,0,iNum-1);
gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);
printf("Time taken %.6lf\n",dEnd-dStart);
printf("\nSorted Array\n");
fnDispArray(iaArr,iNum);
return 0;
}
void fnMerge(int a[], int low, int mid, int high)
{
int i,k,j,b[100];
i=k=low;
j=mid+1;
while(i<=mid && j<=high)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=mid)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(i=low;i<k;i++)
a[i]=b[i];
}
void fnMergeSort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
fnMergeSort(a,low,mid);
fnMergeSort(a,mid+1,high);
fnMerge(a,low,mid,high);
}
}
void fnGenRandInput(int x[], int n)
{
int i;
srand(time(NULL));
for(i=0;i<n;i++)
{
x[i] = rand()%10000;
}
}
void fnDispArray( int x[], int n)
{
int i;
for(i=0;i<n;i++)
printf(" %5d \n",x[i]);
}
OUTPUT
Program:
#include<stdio.h>
int main()
{
int i,j,k,n,a[10][10],indegree[10],flag[10],count=0,s[10],t=0,u;
system("clear");
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
{
indegree[i]=0;
flag[i]=0;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
indegree[i]=indegree[i]+a[j][i];
for(i=1;i<=n;i++)
printf("Indegree of %d is %d\n",i,indegree[i]);
printf("The topological ordering is:");
while(count < n)
{
for(k=1;k<=n;k++)
if((indegree[k]==0)&&(flag[k]==0))//remove vertex which is having indegree 0
s[t++]=k;
u = s[--t];
printf("%d\t",u);
flag[u]=1;
for(i=1;i<=n;i++)
if(a[u][i]==1)
indegree[i]--;
count++;
}
}
OUTPUT 1
Indegree of 1 is 0
Indegree of 2 is 0
Indegree of 3 is 2
Indegree of 4 is 1
Indegree of 5 is 2
OUTPUT 2
AlgorithmKnapsack(n,m,w,p,v)
// Purpose : To find the optimal solution for knapsack problem
// Input : n- Number of object to be selected
m- Capacity of the knapsack
w- Weight of all the object
p- Profit of all the object
// Output : v- The optimal solution for the number selecte with specified remaining capacity
for ß 0 to n do
for ß 0 to m do
if(i=0 or j=0)
v[i,j]=0
else if(w[i]>j)
v[i,j]=v[i-1,j]
else
v[i,j]=max(v[i-1,j] , v[i-1,j-w[i]]+p[i])
end if
end for
end for
return
Program:
#include<stdio.h>
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
void knapsack(int m,int n,int w[],int p[])
{
int v[10][10],x[10],i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
if(j==0||i==0)
v[i][j]=0;
else
if(j<w[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
}
printf("\nTHE SOLUTION TABLE \n");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
printf("%d\t",v[i][j]);
printf("\n");
}
printf("\nTHE OPTIMAL SOLUTION IS:%d",v[n][m]);
for(i=1;i<=n;i++)
x[i]=0;
i=n;
j=m;
while(i!=0&&j!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
}
i--;
}
printf("\nTHE ITEMS SELECTED ARE:");
for(i=1;i<=n;i++)
printf("x[%d]=%d\n",i,x[i]);
}
void main()
{
int w[10],p[10],i,m,n;
system(" clear");
printf("\n ENTER THE NUMBER OF ITEMS:");
scanf("%d",&n);
printf("\n ENTER THE WEIGHTS OF THE ITEMS:\n");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("\n ENTER THE PROFITS OF THE ITEMS:\n");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("\n ENTER THE CAPACITY OF KNAPSACK:");
scanf("%d",&m);
knapsack(m,n,w,p);
}
OUTPUT
6. From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm.
Algorithm Single_source_shortest_path(v,cost,dist,n)
//dist[j],1<=j<=n,is the length of the shortest path from vertex v to vertex j in
//digraph G with n verices. dist[v] is set of 0. G is represented by its cost adjacency
//matrix cost[1:n,1:n].
{
for iß1 to n do
{
//initialize S
S[i]=false
dist[i]ßcost[v,i]
}
S[v]ßtrue
dist[v]ß0.0 //put v in S
for numß2 to n do
{
//determine n-1 paths from v
Choose u from V-S such that dist[u] is minimum
S[u]ßtrue //put u in S
for(each w adjacent to u with S[w]=false) do
//Update distances
if(dist[w]>dist[u]+cost[u,w])than
dist[w]ßdist[u]+cost[u,w]
}
}
Program:
#include<stdio.h>
void dijj(int,int,int [][10],int[],int[]);
void main()
{
int dest,n,s,i,j,cost[10][10],dist[10],path[10];
printf("\nEnter no.of vertices");
scanf("%d",&n);
printf("\n Enter cost adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
printf("\nEnter source vertex");
scanf("%d",&s);
dijj(n,s,cost,dist,path);
printf("\nShortest path \n");
for(i=1;i<=n;i++)
{
dest=i;
if(i!=s)
{
if(dist[i]==9999)
printf("\nvertex %d is not reachable",i);
else
{
printf("\nShortest distance from %d to %d is %d\n",s,i,dist[i]);
while(dest!=s)
{
printf(" %d<-",dest);
dest=path[dest];
}
printf("%d\n",dest);
}
}
}
}
OUTPUT
Enter no.of vertices
6
Shortest path
Shortest distance from 1 to 2 is 80
2<-1
7. Sort a given set of elements using the Quicksort method and determine the time required
to sort the elements. Repeat the experiment for different values of n, the number of elements
in the list to be sorted and plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.
Algorithm quicksort(p,q)
//Sorts the elements a[p],…..a[q] which reside in the global
//array a[1:n] into ascending order;a[n+1] is considered to
//be defined and must be >= all the elements in a[1:n].
{
if(p<q) then
{
//divide P into two subproblems.
j:=Partition(a,p,q+1);
//j is the position of the portioning element.
quicksort(p,j-1);
quicksort(j+1,q);
}
}
Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
int main()
{
system("clear");
struct timeval tv;
double dStart,dEnd;
int a[100],iNum;
printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(a,iNum);
fnDispArray(a,iNum);
gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);
quicksort(a,0,iNum-1);
gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);
printf("\n\nTime taken by quicksort %.6lf\n",dEnd-dStart);
printf("\nSorted Array\n");
fnDispArray(a,iNum);
return 0;
}
OUTPUT
Unsorted Array
101 464 157 918 555 878 504 39 211 321
Sorted Array
39 101 157 211 321 464 504 555 878 918
N Time
10 0.000003
20 0.000005
30 0.000006
40 0.000007
50 0.000009
8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm.
Algorithm Kruskal(E,cost,n,t)
{
// E is the set of Edges in G. G has n vertices.
// cost[u,v] is the cost of edge[u,v]
// T is the set of edges in Minimum Cost Spanning Tree. The total cost is returned as
Output.
Construct a heap out of the edge costs using heapify.
for iß1 to n do parent[i]ß -1
// each vertex is in a different set.
iß0
mincostß0.0
while((i<n-1)and(heap not empty))do
{
Delete a minimum cost edge(u,v) from the heap and reheapify using Adjust
jßfind(u)
kßfind(v)
if(j≠k) then
{
ißi+1
t[i,1]ßu
t[i,2]ßv
mincostßmincost+cost[u,v]
union(j,k)
}
}
if(i≠n-1) then write(“no spanning tree”)
else return mincost
}
Program:
#include<stdio.h>
#include<stdlib.h>
int parent[10],min,n,i,count=1,cost[10][10],sum=0;
void main()
{
int a,u,b,v,j;
system("clear");
printf("Enter the no of vertices:");
scanf("%d",&n);
printf("Enter the cost matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
for(i=1;i<=n;i++) parent[i]=i;
while(count < n)
{
for(i=1,min=99;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j] < min && cost[i][j] != 0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(min == 99)
{
system("clear");
printf("\n No spanning tree \n");
exit(1);
}
while(parent[u]!=u)
u=parent[u];
while(parent[v]!=v)
v=parent[v];
if(u!=v)
{
count++;
printf("\nEdge <%d %d> = %d",a,b,min);
sum+=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Cost of MST %d",sum);
Output:
Enter the no of vertices:6
Enter the cost matrix
09. Check whether a given graph is connected or not using DFS method.
Algorithm:
DFS(G)
//Implemnts a depth-first search traversal of a given graph
//Input:Graph G={V.E}
//Output:Graph G with its vertices marked with consecutive integers in the order they’ve been
first encountered by the DFS traversal mark each Vertex in V with 0 as a mark of being
“unvisited”
Count<-0
For each vertex v in V do
If v is marked with 0
Dfs(v)
//visits recursively all the unvisited vertices connected to vertex v and
//assigns them the numbers in the order they are encountered
//via global variable count
Count<-count+1;mark v with count
For each vertex w in V adjacent to v do
If w is marked with 0
Dfs(w)
Program:
#include<stdio.h>
int adj[20][20], n ,s,visit[20], count=1;
void dfs(int);
int main()
{
int i,j;
system("clear");
printf("Enter the number of vertices:");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&adj[i][j]);
for(i=1;i<=n;i++)
visit[i]=0;
dfs(1);
if (count==n)
printf("\nThe graph is connected");
else
printf("\nThe Graph is not connected.");
}
void dfs(int v)
{
int w;
visit[v]=1;
for(w=1;w<=n;w++)
if ((adj[v][w]==1) && (visit[w]==0))
{
dfs(w);
count++;
}
}
OUTPUT
Algorithm
Algorithm sumOfSubset(s, k, r)
{
//s – partial sum, k – k element in consideration, r – remaining sum
X[k]=1;
if (S+W[k]=m) then
write(X[1:k]); // there is no recursive call here as W[j]>0,1<=j<=n.
else if (S+W[k]+W[k+1]<=m) then
sumofsubset (S+W[k], k+1,r- W[k]);
#include<stdio.h>
#include<math.h>
int s[30], x[30], d, n; //Global variables
int flag=0;
//Function to find optimal subset
void subset(int m, int k, int r)
{
int i,c=0;
x[k]=1; //Mark kth element as included
if (m+s[k]==d) //If inclusion gives sum as d,
{
printf("\nSubset %d:{",++c );
for(i=1;i<=n;i++) //print the elements of the subset
if (x[i]==1)
{
printf("%d ",s[i]);
flag=1; //Set flag to indicate existence of subset
}
printf("}\n");
}
else
{
if (m+s[k]+s[k+1]<=d) //Else check for next element
{
subset(m+s[k],k+1,r-s[k]); //Include next element in subset
x[k+1]=0;
}
if ((m+r-s[k]>=d) && (m+s[k+1]<=d))
{
x[k]=0;
subset(m,k+1,r-s[k]);
x[k+1]=0;
}
}
}
void main()
{
int sum=0,i;
system("clear");
printf("\nEnter the number of elements in the set:");
scanf("%d",&n);
printf("\nEnter Set in increasing order:");
for(i=1;i<=n;i++)
scanf("%d", &s[i]);
printf("\nEnter Maximum subset value: ");
scanf("%d",&d); //Input maximum sum limit
for(i=1;i<=n;i++)
sum= sum+s[i]; //Calculate sum of all set elements
if (sum<d||s[1]>d) //Check for necessary conditions
printf("\nNo subset possible");
else
{
subset(0,1,sum); //Call function to find optimal subset
if (flag==0) //Display message if no suitable subset is found
printf("\nNo subset possible");
}
}
OUTPUT
No subset possible
OUTPUT