0

I've implemented Prim's algorithm in C (www.bubblellicious.es/prim.tar.gz) but I was just wondering how to transform this into Kruskal's algorithm.

It seems they're quite similar, but I can't imagine how can I modify my old code into that new one. It'd be delicious if you give some advices or something. I know that's easy, but I'm still a n00b in C programming ...

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    You are much more likely to get a useful response if you post the relevant code inline in the question. Prim's algorithm is only four lines of pseudo-code so I can't believe that a tarball of half a dozen files is necessary. – ire_and_curses Sep 03 '09 at 08:58
  • Well, you can read only the main file, coz it's no necessary to look at all the files. –  Sep 03 '09 at 09:06
  • 2
    IMHO those algorithms aren't similar enough that it's profitable to convert from one to the other -- Prim's requires some sort of priority queue, while Kruskal's involves a global sorted list of edges. You're better off starting from scratch. – j_random_hacker Sep 03 '09 at 09:08

3 Answers3

5

Why not just write Kruskal's from scratch and see how they compare in your own solutions? Best way to learn.

Pod
  • 3,938
  • 2
  • 37
  • 45
1

To convert you need a forest (i.e. a set of trees where initially each node is a tree) as your temporary output structure rather than a single tree. Then on each step, rather than finding the cheapest vertex that adds a currently unconnected node to your tree, you find the cheapest edge in the graph and, if it creates a new tree (i.e. connects two previously unconnected nodes) add that tree to the forest and remove the source trees. Otherwise discard the edge. A proper implementation of Kruskal is more memory intensive but less time intensive than a proper Prim implementation.

But the differences between the two are quite large. Probably all you can keep between are some helper functions and some data structures. Not a conversion, more a rewrite using more high level building blocks.

jilles de wit
  • 7,060
  • 3
  • 26
  • 50
0

Why dont you consider switching to C++ and using the boost graph library (http://www.boost.org/)?

It contains very well implementations for both algorithms. Type-safe and highly performant. See kruskal_minimum_spanning_tree and prim_minimum_spanning_tree

RED SOFT ADAIR
  • 12,032
  • 10
  • 54
  • 92