Tuesday, September 04, 2007

Studying D Programming Language...

I have recently decided to re-hash (sic) my algorithms, and to study the D Programming Language at the same time. Below you can see a cool heapsort implementation.

As I used the ZeroBUGS debugger to step through the code, I have noticed that the DMD compiler does not generate debugging info for the template parameters (a and b in swap, a in siftdown, and so on). I hope this glitch (and other related bugs) will be fixed before the next D Programming Language conference.


import std.stdio;

void swap(T)(inout T a, inout T b)
{
scope tmp = a;
a = b;
b = tmp;
}

void siftdown(T)(inout T a, int begin, uint end)
{
uint root = begin;
while (root * 2 + 1 <= end)
{
scope child = root * 2 + 1;
if (child < end && a[child + 1] > a[child])
{
++child;
}
if (a[root] < a[child])
{
swap(a[root], a[child]);
root = child;
}
else
{
break;
}
}
}

void heapify(T)(inout T a, uint length)
{
int start = length / 2 + 1;

while (start >= 0)
{
siftdown(a, start, length - 1);
--start;
}
}

void heapsort(T)(inout T a)
{
uint count = a.length;
heapify(a, count);

--count;
while (count > 0)
{
swap(a[0], a[count]);
--count;
siftdown(a, 0, count);
}
}

void main()
{
long[] a = [ 5, 4, 1, 2, 100, 10, 42, 5, 10 ];
writefln(a);

writefln("----- heapsort -----");
heapsort(a);
writefln(a);
}

No comments: