1

I was trying to implement Prim's algorithm using min Heap. here is the link I was referring to https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-6/

I was wondering why can we use a vector and sort it using std::sort function in place of min heap.

cgDude
  • 93
  • 1
  • 8
  • Please, don't provide links as first source of info. Instead, copy/paste the relevant parts (maybe prefixed with `> ` to mark them as cite) and provide the link for reference additionally. – Scheff's Cat May 09 '20 at 13:34

1 Answers1

0

You could, but remember that every time a new node is added to the MST you have to update the set of edges that cross the partition (edges to nodes that are not yet in the MST), so you would have to sort your vector at every iteration of the algorithm, which would waste time, since you just need to know which of the edges that cross the partition has the minimum value at that iteration, the min-heap is optimal for that operation since its time complexity for extracting the minimum value is O(log n) while the sort is O(n log n) which can make the algorithm run slower on large or dense graphs.

Matias Agelvis
  • 951
  • 2
  • 11
  • 22
  • can we use set with same time complexity like min-heap? – cgDude May 09 '20 at 18:16
  • Sure, a `std::set` would do the trick, the only detail is that it doesn't allow for repeated elements, so in the case that there are several possible MST's for the graph, you will get consistently the same one, which depends on the order on which you iterate over the crossing edges, but that could only be an issue if you are asked explicitly to get a particular MST or all the possible MST's, otherwise you're good. – Matias Agelvis May 10 '20 at 14:58
  • Just some thing else, if you where to use a `std::set` you would need to use a struct to hold the weight of the edge and the id's of the nodes connected by it and also define a comparison function for it to compare the items, a `std::map` with the weight of the edge as the key and the id of the node not yet in the MST, this approach archives the same result more easily, that's how I implemented it back then. – Matias Agelvis May 11 '20 at 02:32