def prim(G, s): """ Implementation of Prims to find MST """ for v in G.V: v.rank = sys.maxsize v.p = None s.rank = 0 Q = MinHeap(G.V) while Q.size() > 0: u = Q.extract_min() for v, weigth in G.adj(u): if v in Q and weigth < v.rank: # updates the predecessor and rank such that we are getting spanning tree with lowest total edge weight v.p = u v.rank = weigth # update heap since ranks have changed Q.build_min_heap() # find all the edges that spans the tree result = [] total_weight = 0 for u in G.V: for v, weigth in G.adj(u): if v.p == u and (u, v, weigth) not in result: result.append((u, v, weigth)) total_weight += weigth print(result, "Minimal weight:", total_weight)
def heapsort(a): a = list(a) heap = MinHeap() heap.heapify(a) a_sorted = [] while heap.peek(): a_sorted.append(heap.extract_min()) return a_sorted