0% found this document useful (0 votes)
14 views53 pages

ADA Lab Manual

Lab manual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views53 pages

ADA Lab Manual

Lab manual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

1.

Sort a given set of elements using the quick 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. the elements
can be read from a file or can be generated using the random number generator

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#include<dos.h>
#include<graphics.h>

void quicksort(int[],int,int);
int partition(int[],int,int);
void plotgraph(double time[],int ele[],int);

void main()
{
int i,n,a[20],ch=1;
double time[20],t;
int ele[20],k=0;
clock_t start,end;
clrscr();

while(ch)
{
start=clock();

printf("Enter the number of elements : ");


scanf("%d",&n);
printf("\n The array elements are \n");
for(i=0;i<n;i++)
{
a[i]=(int)rand()%1000;

printf("%d\t", a[i]);
}
quicksort(a,0,n-1);

printf("\nThe sorted array elements are \n");


for(i=0;i<n;i++)
printf("\t %d",a[i]);

end=clock();

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

printf("\n Timetaken =%lf",t);

time[k]=t;
ele[k]=n;
k++;

printf("\n Do u want to continue (0/1) \n");


scanf("%d",&ch);
}

clrscr();
printf("\n Plot a graph");
printf("\nTime took ");
for(i=0;i<k;i++)
printf(" \n Elements = %d and Time = %lf",ele[i],time[i]);

getch();

clrscr();

plotgraph(time,ele,k);
}

void plotgraph(double time[],int ele[],int n)


{
int gd = DETECT, gm;

int i,x1,x2,y1,y2;
int s=100;
char str[100];

initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

/* Initialize the variable */


x1 = 50;
x2 = 50;
y1 = 350;
y2 = 350;

clrscr();

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


{
sprintf(str, "%d", ele[i]);
/* Display the data label year */
outtextxy(s,375,str);
s= s + 50;
}

printf("\t\t\tBAR CHART\n");
setfillstyle(SOLID_FILL,RED);
/* Display the data */
for(i=0;i<n;i++)
{
printf("\nElements = %d Time : %lf",ele[i],time[i]);

y2=y2 - int(time[i]*10);
x2=x2+50;
x1=x2+10;

bar(x1,y1,x2,y2);

y2 = 350;
}
/* Close the Graph */
getch();
closegraph();
}

void quicksort(int a[],int low,int high)


{
int mid;

if(low<high)
{
mid=partition(a,low,high);

quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}

int partition(int a[],int low,int high)


{
int key,i,j,temp,k;

key=a[low];
i=low+1;
j=high;

while(i<=j)
{
while(i<=high && key>=a[i])
i=i+1;

while(key<a[j])
j=j-1;

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
k=a[j];
a[j]=a[low];
a[low]=k;
}
}
return j;
}
2. Implement merge sort algorithm to sort a given set of elements and determine the time
required to sort the elements. Repeat the experiment for the different values of n, the
number of elements in the list to be sorted. The elements can be read from a file or can be
generated using random generator.

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
void Merge(int a[], int low, int mid, int high)
{
int i,j,k,b[20];
i=low;
j=mid+1;
k=low;

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(k=low; k<=high; k++)


a[k] = b[k];
}
void MergeSort(int a[], int low, int high)
{
int mid;

if(low >= high)


return;

mid = (low+high)/2;

MergeSort(a, low, mid);


MergeSort(a, mid+1, high);

Merge(a, low, mid, high);


}

void main()
{
int n, a[2000],k;
clock_t st,et;
double ts;
int ch=1;

clrscr();

while(ch)
{
st=clock();

printf("\n Enter How many Numbers:");


scanf("%d", &n);

printf("\nThe Random Numbers are:\n");


for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}

MergeSort(a, 1, n);

printf("\n Sorted Numbers are : \n ");

for(k=1; k<=n; k++)


printf("%d\t", a[k]);

et=clock();

ts=(double)(et-st)/CLOCKS_PER_SEC;

printf("\nThe time taken is %lf",ts);

printf("\nDo you want continue : ");


scanf("%d",&ch);
}
}
3. Write a program to sort a list of N elements using Selection Sort Technique
#include <stdio.h>
#include<conio.h>
void main()
{
int a[100], n, i, j, position, swap;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter %d Numbers : \n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("\nSorted Array: \n");
for(i = 0; i < n; i++)
printf("%d\n", a[i]);
getch();
}

5. Write a program to implement Dynamic programming algorithm for the 0/1 Knapsack
Problem
#include<stdio.h>
#include<conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));

v[i][j]=value;
}
return(v[i][j]);
}

void main()
{
int profit,count=0;
clrscr();

printf("\nEnter the number of elements\n");


scanf("%d",&n);

printf("Enter the profit and weights of the elements\n");


for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}

printf("\nEnter the capacity \n");


scanf("%d",&cap);

for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;

profit=knap(n,cap);
i=n;
j=cap;

while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}

printf("Items included are\n");


printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
getch();
}
6. Write a program to perform Knapsack problem using Greedy Solution.
#include<stdio.h>
#include<conio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0;
int i, j, u;
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("\nThe result vector is:- ");


for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);

void main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &num);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}

printf("\nEnter the capacityacity of knapsack:- ");


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);


getch();
}
7. Write a program to implement the DFS and BFS algorithm for a graph.

#include<stdio.h>
#include<conio.h>

int q[20],front=-1,rear=-1,a[20][20],vis[20];

void DFS(int,int);
int qdelete();
void add(int item);
void bfs(int s,int n);

void main()
{
int n,i,s,j;
clrscr();

printf("ENTER THE NUMBER VERTICES ");


scanf("%d",&n);

printf("Enter the adjancey matrix\n");


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

printf("THE ADJACENCY MATRIX IS\n");


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

printf("ENTER THE SOURCE VERTEX :");


scanf("%d",&s);

for(i=1;i<=n;i++)
vis[i]=0;

printf("\n D F S\n");
DFS(s,n);

for(i=1;i<=n;i++)
vis[i]=0;

printf("\n B F S\n");
bfs(s,n);

getch();
}

//**************BFS(breadth-first search) code**************//


void bfs(int s,int n)
{
int p,i;

add(s);
vis[s]=1;

p=qdelete();
if(p!=0)
printf("\t %d",p);

while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}

p=qdelete();

if(p!=0)
printf("\t %d ",p);
}

for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==-1)
front++;

q[++rear]=item;
}
int qdelete()
{
int k;

if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

void DFS(int i,int n)


{
int j;

printf("\t%d",i);

vis[i]=1;

for(j=1;j<=n;j++)
if(!vis[j]&&a[i][j]==1)
DFS(j,n);
}
8. Write a program to find minimum and maximum value in an array using divide and
conquer.
#include<stdio.h>
#include<conio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
}
}
else
{
mid = (i+j)/2;
maxmin(i, mid);
max1 = max;
min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
}
}
}
void main ()
{
int i, num;
clrscr();
printf ("\nEnter the total number of numbers : ");
scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);

max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array : %d\n", min);
printf ("Maximum element in an array : %d\n", max);
getch();
}

9. Write a test program to implement Divide and Conquer Strategy. Ex: Quick Sort
algorithm for sorting list of integers in ascending order.
#include<stdio.h>
#include<conio.h>

void quicksort(int[],int,int);
int partition(int[],int,int);

void main()
{
int i,n,a[20];

clrscr();

printf("Enter the number of elements : ");


scanf("%d",&n);
printf("Enter the %d array elements : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

quicksort(a,0,n-1);

printf("The sorted array elements are \n");


for(i=0;i<n;i++)
printf("\n%d",a[i]);

getch();
}

void quicksort(int a[],int low,int high)


{
int mid;

if(low<high)
{
mid=partition(a,low,high);

quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}

int partition(int a[],int low,int high)


{
int key,i,j,temp,k;
key=a[low];
i=low+1;
j=high;

while(i<=j)
{
while(i<=high && key>=a[i])
i=i+1;

while(key<a[j])
j=j-1;

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

return j;
}
10. Write a program to implement Merge Sort Algorithm for sorting a list of integers in
ascending order.

#include<stdio.h>
#include<conio.h>

void Merge(int a[], int low, int mid, int high)


{
int i,j,k,b[20];
i=low;
j=mid+1;
k=low;

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(k=low; k<=high; k++)


a[k] = b[k];
}
void MergeSort(int a[], int low, int high)
{
int mid;

if(low >= high)


return;

mid = (low+high)/2;

MergeSort(a, low, mid);


MergeSort(a, mid+1, high);

Merge(a, low, mid, high);


}

void main()
{
int n, a[20],i;

clrscr();

printf("\n Enter size of Array : ");


scanf("%d", &n);

printf("\n Enter %d numbers : \n",n);


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

MergeSort(a, 0, n-1);

printf("\n Sorted Numbers are : \n ");


for(i=0; i<n; i++)
printf("%d\t", a[i]);

getch();
}
PART B
3. Write a C program that accepts the vertices and edges for a graph and stores it as an adjacency
matrix
#include<stdio.h>
#include<conio.h>
#define MAX 100

int adj[MAX][MAX];
int n;

void main()
{
int max_edges,i,j,origin,destin;
int graph_type;
clrscr();

printf("1. Undirected graph\n 2. Directed graph\n");


printf("\nEnter your choice : ");
scanf("%d",&graph_type);

printf("Enter number of vertices : ");


scanf("%d",&n);

printf("Enter number of edges : ");


scanf("%d",&max_edges);

for(i=1; i<=max_edges; i++)


{
printf("Enter edge [ %d ] : ",i);
scanf("%d %d",&origin,&destin);
if( origin>n || destin>n || origin<1 || destin<1)
{
printf("\nInvalid vertex!\n");
i--;
}
else
{
adj[origin][destin] = 1;
if( graph_type == 1) /*if undirected graph*/
adj[destin][origin] = 1;
}
}

printf("\nThe adjacency matrix is :: \n");


for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
printf("%4d",adj[i][j]);
printf("\n");
}

getch();
}
4. Write a program to implement a function print In-Degree, Out-Degree and display that
adjacency matrix
#include<stdio.h>
#include<conio.h>
#define MAX 100

int adj[MAX][MAX]; /*Adjacency matrix*/


int n; /*Number of vertices in the graph*/

void main()
{
int max_edges,i,j,origin,destin;
int graph_type;
int in_deg,out_deg,deg;
clrscr();
printf("1. Undirected graph\n 2. Directed graph");
printf("\nEnter your choice : ");
scanf("%d",&graph_type);

printf("Enter number of vertices : ");


scanf("%d",&n);

printf("Enter number of edges : ");


scanf("%d",&max_edges);

for(i=1; i<=max_edges; i++)


{
printf("Enter edge [ %d ] : ",i);
scanf("%d %d",&origin,&destin);

if( origin>n || destin>n || origin<1 || destin<1)


{
printf("\nInvalid vertex!\n");
i--;
}
else
{
adj[origin][destin] = 1;
if( graph_type == 1) /*if undirected graph*/
adj[destin][origin] = 1;
}
}/*End of for*/

printf("The adjacency matrix is :: \n");


for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
printf("%4d",adj[i][j]);

printf("\n");
}

if(graph_type==1)
{
printf("Vertex \t Degree ");
for ( i = 1 ; i <= n ; i++ )
{
deg = 0;

for ( j = 1 ; j <= n ; j++ )


if ( adj[i][j] == 1)
deg++;
printf("\n %5d \t\t %d", i, deg);
}
}
else
{
printf("Vertex \t In_Degree \t Out_Degree \t Total_Degree ");

for (i = 1; i <= n ; i++ )


{
in_deg = out_deg = 0;
for ( j = 1 ; j <= n ; j++ )
{
if ( adj[j][i] == 1 )
in_deg++;
}
for ( j = 1 ; j <= n ; j++ )
if (adj[i][j] == 1 )
out_deg++;
printf("\n %5d\t\t%d\t\t%d\t\t%d",i,in_deg,out_deg,in_deg+out_deg);
}
}
getch();
}/*End of main()*/
5. Write program to implement backtracking algorithm for solving problems like N queens
#include<stdio.h>
#include<conio.h>
#include<math.h>

int board[20],count;

void main()
{
int n,i,j;
void queen(int row,int n);
clrscr();

printf(" - N Queens Problem Using Backtracking -");


printf("\n\nEnter number of Queens:");
scanf("%d",&n);

queen(1,n);

printf("\nTotal number of Solutions = %d",count);


getch();
}

//function for printing the solution


void print(int n)
{
int i,j;

printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)
printf("\t%d",i);

for(i=1;i<=n;++i)
{
printf("\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}
/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
int i;

for(i=1;i<=row-1;++i)
{
//checking column and digonal conflicts
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}

return 1; //no conflicts


}

//function to check for proper positioning of queen


void queen(int row,int n)
{
int column;

for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}

6. Write a program to implement backtracking algorithm for the sum of subsets problem.
#include<stdio.h>
#include<conio.h>

int s[10],x[10],d;
void sumofsub(int,int,int);
void main()
{
int n,sum=0;
int i;
clrscr ();

printf("\nEnter the size of the set : ");


scanf ("%d",&n);

printf("\n Enter the set in increasing order:\n");


for(i=1;i<=n;i++)
scanf("%d",&s[i]);

printf("\nEnter the value of d: ");


scanf("%d",&d);

for(i=1; i<=n; i++)


sum=sum+s[i];

if(sum<d || s[1]>d)
printf("\n No subset possible : ");
else
sumofsub(0,1,sum);

getch();
}

void sumofsub(int m,int k,int r)


{
int i=1;

x[k]=1;

if((m + s[k]) == d)
{
printf("Subset:");
for(i=1;i<=k;i++)
if(x[i] == 1)
printf("\t%d",s[i]);

printf("\n");
}
else
if(m+s[k]+s[k+1]<=d)
sumofsub(m+s[k],k+1,r-s[k]);
if ((m+r-s[k]>=d) && (m+s[k+1]<=d))
{
x[k] = 0;
sumofsub (m,k+1,r-s[k]);
}
}
7. Write a program to implement greedy algorithm for job sequencing with deadlines
#include<stdio.h>
#include<conio.h>
#define MAX 100

typedef struct Job {


char id[5];
int deadline;
int profit;
}Job;

void jobSequencingWithDeadline(Job jobs[], int n);

int minValue(int x, int y)


{
if(x < y)
return x;

return y;
}

void main()
{
int i, j;
clrscr();

//jobs with deadline and profit


Job jobs[5] = {
{"j1", 2, 60},
{"j2", 1, 100},
{"j3", 3, 20},
{"j4", 2, 40},
{"j5", 1, 20},
};

//temp
Job temp;

//number of jobs
int n = 5;

//sort the jobs profit wise in descending order


for(i = 1; i < n; i++)
{
for(j = 0; j < n - i; j++)
{
if(jobs[j+1].profit > jobs[j].profit) {
temp = jobs[j+1];
jobs[j+1] = jobs[j];
jobs[j] = temp;
}
}
}

printf("%10s %10s %10s\n", "Job", "Deadline", "Profit");


for(i = 0; i < n; i++)
{
printf("%10s %10i %10i\n", jobs[i].id, jobs[i].deadline, jobs[i].profit);
}

jobSequencingWithDeadline(jobs, n);
getch();
}

void jobSequencingWithDeadline(Job jobs[], int n)


{
//variables
int i, j, k, maxprofit;

//free time slots


int timeslot[MAX];

//filled time slots


int filledTimeSlot = 0;

//find max deadline value


int dmax = 0;
for(i = 0; i < n; i++)
{
if(jobs[i].deadline > dmax)
{
dmax = jobs[i].deadline;
}
}

//free time slots initially set to -1 [-1 denotes EMPTY]


for(i = 1; i <= dmax; i++)
{
timeslot[i] = -1;
}
printf("dmax: %d\n", dmax);

for(i = 1; i <= n; i++)


{
k = minValue(dmax, jobs[i - 1].deadline);
while(k >= 1) {
if(timeslot[k] == -1) {
timeslot[k] = i-1;
filledTimeSlot++;
break;
}
k--;
}

//if all time slots are filled then stop


if(filledTimeSlot == dmax) {
break;
}
}

//required jobs
printf("\nRequired Jobs: ");
for(i = 1; i <= dmax; i++) {
printf("%s", jobs[timeslot[i]].id);

if(i < dmax) {


printf(" --> ");
}
}

//required profit
maxprofit = 0;
for(i = 1; i <= dmax; i++) {
maxprofit += jobs[timeslot[i]].profit;
}
printf("\nMax Profit: %d\n", maxprofit);
}
8. Write a program to implement dynamic programming algorithm for the optimal Binary
search tree problem
#include <stdio.h>
#include<conio.h>
#define INT_MAX 999

int sum(int freq[], int low, int high)


{
//sum of frequency from low to high range
int sum = 0;
for (int k = low; k <=high; k++)
sum += freq[k];
return sum;
}

int minCostBST(int keys[], int freq[], int n)


{
int cost[10][10];

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


//when only one key, move along diagonal elements
cost[i][i] = freq[i];

for (int length=2; length<=n; length++)


{
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 infinity

for (int r=i; r<=j; r++)


{
//find cost when r is root of subtree
int c = ((r > i)?cost[i][r-1]:0)+((r < j)?cost[r+1][j]:0)+sum(freq, i, j);
if (c < cost[i][j])
cost[i][j] = c;
}
}
}
return cost[0][n-1];
}

void main() {
clrscr();
int keys[20];
int freq[20];
int n,i;

printf("Enter size : ");


scanf("%d",&n);

printf("Enter %d keys and freq values ",n);


for(i=0;i<n;i++)
scanf("%d %d",&keys[i],&freq[i]);

printf("Cost of Optimal BST is: %d",minCostBST(keys, freq, n));

getch();
}
9. Write a program that implements Prim’s algorithm to generate minimum cost spanning
tree.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
clrscr();

printf("\n\tImplementation of Prim's algorithm\n");

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();
}
10. Write a program that implements Kruskal’s algorithm to generate minimum cost
spanning tree.
#include<stdio.h>
#include<conio.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()
{
clrscr();
printf("\n\tImplementation of Kruskal's algorithm\n");

printf("\nEnter the no. of vertices:");


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("\n\tMinimum 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;
}

You might also like