The Difference Between Prime and Kruskal

Kruskal Algorithm

int MST_Kruskal (G, w)
{
    A = {};
    for each vertex v in G.V            // O(V)
    Make_Set(v);
    sort all edges in G.E               // O(ElogE) = O(ElogV)
    for each edge(u, v) in G.E
        if Find_Set(u) != Find_Set(v)
            // repeate at most V-1 times
            // and each time O(log(V))   
            A = A + {u,v};
            Union(u, v);
        if A == G.V
            break
    return A
    // total complexity for Kruskal is 0(ElogV)
}

Prime Algorithm

int MST_Prime (G,w)
{
    A = {};
    heapE = {}; //heap for edges
    A = A + {G.V[0]}, heapE.insert(G.V[0].edges); //initial

    while (A != G.V){
        edge(u, v) = heapE.pop();     // fiboHeap O(1), minHeap 0(logE) = 0log(V)
        if v not in A{                // repeat at most V-1 times
            heapE.insert(v.edges);    // fiboHeap O(1), minHeap 0(logE) = O(logV)               
        }
    }
    // we can insert the valuable edges only
    // so totally E inserts, V minimum choices
    // total complexity for Prime is:
    // 0(VlogV + E) for fiboHeap, and O(ElogV) for minHeap
}

Analysis for Prime Algorithm

Prim's algorithm select the edge with the lowest weight between the group of vortexes already selected and the rest of the vortexes. So to implement Prim's algorithm, you need a minimum heap. Each time you select an edge you add the new vortex to the group of vortexes you've already chosen, and all its adjacent edges go into the heap. Then you choose the edge with the minimum value again from the heap.

So the times we get are:

With Fibonacci heap:
Choosing minimum edge = O(time of removing minimum) = O(log(E)) = O(log(V))
Inserting edges to heap = O(time of inserting item to heap) = 1
With Min heap:
Choosing minimum edge = O(time of removing minimum from heap) = O(log(E)) = O(log(V))
Inserting edges to heap = O(time of inserting item to heap) = O(log(E)) = O(log(V))

Remember that E =~ V^2 ... so log(E) = log(V^2) = 2Log(V) = O(log(V)

In total you have E inserts, and V minimum choosings (It's a tree in the end).

So using Min heap you'll get: O(Vlog(V) + Elog(V)) = O(Elog(V))

And using Fibonacci heap you'll get: O(Vlog(V) + E)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 【咱大中华,泱泱大国,教师多如牛毛,被孽徒杀死多少是不必以为不幸的,哼哼!死者长已矣,存者且欢笑。鲍方老师的被...
    琴川先生阅读 1,706评论 1 2
  • “我最讨厌呆在武汉啦啊啊啊啊啊啊啊!” 一棵一棵的枯黄梧桐叶,脉络缱绻微缩的伸向远方。 一株一株的深绿香樟叶,一如...
    大瓜world阅读 2,656评论 0 1
  • 《一条狗的使命》由莱塞·霍尔斯道姆执导,根据W·布鲁斯·卡梅伦同名小说改编,讲述了一条狗贝利经历四生四世重生,在...
    马严阅读 3,093评论 0 0

友情链接更多精彩内容