Algorithm Unit 3
Algorithm Unit 3
For problems that do not call for the selection of an optimal subset, in the greedy method we
make decisions by considering the inputs in some order. Each decision is made using an
optimization criterion that can be computed Using decisions already made. Call this version
of the greedy method the ordering paradigm.
KNAPSACK PROBLEM
void GreedyKnapsack ( float m, int n)
// p[1:n] and w[1:n] contain the profits and weights
// respectively of the n objects ordered such that
//p[i] / w[i] >= p[i++1] / w[i+1]. m is the knapsack
// size and x[1:n] is the solution vector.
{
for (int i=1; i <= n; i++) x[i] = 0.0; //initialize x
float U = m;
for ( i=1; i <= n; i++)
{ if( w[i] > U) break;
x[i] =1.0;
U -= w[i];
}
if (i <= n) x[i] = U / w[i];
}
.
1 float Prim (int E[][SIZE], float cost [] [SIZE], int n, int t[] [2])
2 // E is the set of edges in G. cost[1:n] [1:n] is the cost
3 // adjacency matrix of an n vertex graph such that cost[i] [j] is
4 // either a positive real number or infinity if no edge (i,j) exists.
5 //A minimum spanning tree is computed and stored as a set of
7 // edges in the array t[1:n-1] [1:2].
8 // (t[il] [1], t[i] [2]) is an edge in
9 // the minimum-cost spanning tree.
10 // The final cost is returned.
11 {
12 int near [SIZE], j, k, l;
13 let (k, l)be an edge of minimum cost in E;
14 float mincost = cost[k][l];
15 t[1] [1] = k; t[1] [2] = l;
16 for ( int i = 1; i <= n; i++) // Initialize near.
17 if (cost[i, l] < cost[i] [k]) near [i] = l;
18 else near[i]= k;
19 near[k] = near[l] = 0;
20 for ( i = 2; i <= n-1; i++) { // Find n-2 additional
21 //edges for t.
22 let j be an index such that near[j] != 0 and
23 cost [j] [near[j]] is minimum;
24 t[i] [1] = j; t[i] [2] = near[j];
25 mincost = mincost + cost [j] [near[j]];
26 near[j] = 0;
27 for ( k =1 k <= n; k++) // Update near[].
28 if ((near[k] != 0) &&
29 (cost[k] [near[k]] > cost[k] [j]))
30 near[k] = j;
31 }
32 return (mincost);
33 } (Prim's minimum-costs panning tree algorithm)
Kruskal's Algorithm
Example:
Consider the following graph.
8 }
(Kruskal’s algorithm)