Exp No7
Kruskal’s algorithm
Class edge
{
Public:
Int start_v, end_v;
Int w;
};
Class graph
{
edges e[20];
char city[20][20];
int g[10][10];
public :
graph();
void create();
int search(char *);
void display();
void sort();
void kruskal();
}
Edges e[20]
|
i/p no. of cities & initialize g[20][20] to value 9999; //max value
also i/p cities in city array
}
Create()
{
//directed or undirected optional
i=0; …// index of edges
// input the edges
Do
{
i/p source city sc;
int sc=search(source city name); //returns index of city
e[i].start_v=sc;
1
|
int dest=serach(dc);
2 e[i].end_v=dest;
|
Enter cost of edges;
Cin>>g[source][dest];
e[i].w=g[source][dest];
for undirected graph copy
g[dest][source]=g[source][dest];
i++;
want to continue? y/n
}while (ch==’y’);
}
Void display()
{
Display the matrix (with city names if possible)
}
Void sort()
{
For(i=1 to k edges)
{
Use insertion sort on e[];
}
}
Void kruskal()
{
int sets[no.ofcities]; // to check which vertex is in which set
Sort();
For(i=0 to numofcities) // every node is cycle with itself
sets[i]=i;
For(j=0; j<noofedges; j++)
{
If(sets[e[j].start_v != sets[e[j].end_v]) // if there is no cycle, add the cost & reset cycle status
{
Display start city & end city;
Totalcost=totalcost+e[j].w;
st= sets[e[j].start_v];
ed= sets[e[j].end_v];
for(p=0;p<numofcities;p++)
{
If(sets[p]==ed) // connect previous edge’s end with new edge start in cycle array
sets[p]=st;
}
}
Cout<<totalcost;
}
}
Example: Kruskal
After sorting:
Weight Src Dest
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
Sets array:
Index value
0
|
0
|
1
|
1
|
2
|
2
|
3
|
3
|
4
|
4
|
5
|
5
|
6
|
6
|
7
|
7
|
8
|
8
|
Index value sets[7]=7 != sets[6]=6 st=7 ed=6 check all locations of cycle array to find ed=6 if found mark cycle[p]=st=7
0
|
0
|
1
|
1
|
2
|
2
|
3
|
3
|
4
|
4
|
5
|
5
|
6
|
6/7
|
7
|
7
|
8
|
8
|
sets[8]=8 != sets[2]=2 st=8 ed=2 check all locations of cycle array to find ed=2 if found mark cycle[p]=st=8
After sorting:
Weight Src Dest
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
|
Index value
|
0
|
0
|
|
1
|
1/0
|
|
2
|
2/8/0
|
|
3
|
3/8/0
|
|
4
|
4/0
|
|
5
|
5/7/8/0
|
|
6
|
6/7/8/0
|
|
7
|
7/8/0
|
|
8
|
8/0
|
No comments:
Post a Comment