170 likes | 467 Views
Prim’s algorithm. Begin with a start vertex and no edges Apply the greedy rule Add an edge of min weight that has one vertex in the current tree and the other not in the current tree Continue until you get a single tree T. To implement Prim’s algorithm:. Priority queues
E N D
Prim’s algorithm • Begin with a start vertex and no edges • Apply the greedy rule • Add an edge of min weight that has one vertex in the current tree and the other not in the current tree • Continue until you get a single tree T
To implement Prim’s algorithm: Priority queues • add an element to the queue with an associated priority • remove the element from the queue that has the highest priority, and return it • A simple way to implement a priority queue data type is to keep a list of elements, and search through the list for the highest priority element. • This implementation takes O(1) time to insert an element, and O(n) time for "minimum" or “maximum" • There are many more efficient implementations available.
Define: Key (v) is the minimum weight of any edge connecting v to the tree T, If no such edge it is • Keep all the vertices not included in T in a Priority queue Q • Initialy all the keys is • Pick a start vertex s from Q and add it to T • Key (s)=0 • Update the keys of all the of the vertices in Q that is adjacent to s • From Q, Pick the vertex v with min key and add it to T • Update the keys of all the of the vertices in Q that is adjacent to v • From Q, Pick the vertex with min key and add it to T … and so on until the queue is empty
Prime( Graph G, Vertex root) Q V(G) for each v V key(v) key(root) 0 while (! Empty (Q)) u = delete_min(Q)// delete u with min key(u) for each v Q such that (v, u) E if key(v) > weight(v, u) key(v) = weight(v,u) pred(v) u
g e h f a c d b
O(V) |V| delete_min( ) operations If Q is an array O(V2) O(E) Analyzing prim’s algorithm Prime( Graph G, Vertex root) Q V(G) for each v V key(v) key(root) 0 while (! Empty (Q)) u = delete_min(Q)// delete u with min key(u) for each v Q such that (v, u) E if key(v) > weight(v, u) key(v) = weight(v,u) pred(v) u Time complexity depends on data structure Q O(E+V2)