2. Name the greedy algorithm used in the programand explain the algorithm in detail on how it works with an example.(4 marks)
public class Group4 { private static final int V = 5; int minKey(int key[], BooleanmstSet[]) { int min = Integer.MAX_VALUE,min_index = -1;
for (int v = 0; v < V;v++) if(mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; }
returnmin_index; }
void print(int parent[], intgraph[][]) { for (int i = 1; i < V;i++) System.out.println(parent + " - " + i + "\t" +graph[parent]+'\n'); }
void ABC(int graph[][]) { int parent[] = newint[V]; int key[] = newint[V]; Boolean mstSet[] = newBoolean[V]; for (int i = 0; i < V;i++) { key =Integer.MAX_VALUE; mstSet= false; }
key[0] = 0;
parent[0] = -1;
for (int count = 0; count< V - 1; count++) {
int u =minKey(key, mstSet);
mstSet = true;
for(int v = 0; v < V; v++)
if (graph[v] != 0 && mstSet[v]== false && graph[v] < key[v]) { parent[v] =u; key[v] =graph[v]; } }
print(parent,graph); }
public static void main(String[]args) { Group4 t = newGroup4(); int graph[][] = new int[][]{ { 0, 3, 0, 7, 0 }, {3, 0, 4, 9, 6 }, {0, 4, 0, 0, 8 }, {7, 9, 0, 0, 10 }, {0, 6, 8, 10, 0 }};
t.ABC(graph); } }
2. Name the greedy algorithm used in the program and explain the algorithm in detail on how it works with an example.(
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am