Archive for the ‘Various algorithms’ Category

A heap’s world

Saturday, March 3rd, 2007

This is my first “code” post. I’ve implemented a very basic binary minimum heap in D. A heap is a way to structure your data in a very nice way. It’s running time is quite acceptable, as any operation runs in O(lg n).

A reason to have a min-heap, could be if you wanted to implement the A* path-finding-algorithm. There are of course many more reasons :)

What it does, is keeping track of values along with a key. It sorts the different values according to the key. You can then extract the value that currently has the smallest key.

Here’s the most important lines:

  1. /**
  2. Heap made by Esben Damgaard
  3. Posted on the blog d.hvemder.dk
  4.  
  5. "THE BEER-WARE LICENSE" (Revision 42):
  6. <ebbe _at_ skummer.com> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Esben Damgaard
  7.  
  8. **/
  9.  
  10. void main() {
  11. MinHeap!(char[]) heap = new MinHeap!(char[])();
  12. heap.insert(4, "I should be first out( remember to visit d.hvemder.dk )");
  13. writefln(heap.extractMin() );
  14. ...
  15. };
  16.  
  17. class MinHeap(T) {
  18. ...
  19. public:
  20. void insert(int argKey, T argValue) {
  21. nodes.length = nodes.length + 1;
  22. nodes[length-1] = new Node!(T)(argKey, argValue);
  23. decreaseKey(nodes.length-1, argKey);
  24. }
  25.  
  26. T showMin() {
  27. return nodes[0].getValue();
  28. }
  29.  
  30. T extractMin() {
  31. if( nodes.length < 1 )
  32. return cast(T) null;
  33. T temp = nodes[0].getValue();
  34. nodes[0] = nodes[length-1];
  35. heapify(0);
  36. nodes.length = nodes.length - 1;
  37. return temp;
  38. }
  39. };

As you can see you are welcome to do whatever you want to do with the file, as long a you keep my beer-ware license in the file.

The implementation is still quite simple, and I intend to extend it to be both a min-heap and a max-heap. It should also be possible to change a values key. I haven’t quite figured out how to do that though It could be done by just saving an id along with the insert. You should then be able to search for that id. The running time, though isn’t that good for searching in heaps like this one. It needs a little more thinking.

A smart thing I learned while implementing this, is in line 27. Here it is up to the user to define what type the values should be. This makes the heap very dynamic in what can be stored. In line 13 there’s an example where I create a MinHeap which can store char[]. Nice :)