QSort in D: is this best?

Sean Kelly sean at invisibleduck.org
Sun Dec 20 08:10:25 PST 2009


downs Wrote:

> Or are there any bugs/optimization opportunities I'm missing?
> 
> void qsort(T)(T[] array) {
>   if (array.length < 2) return;
>   static int i;
>   auto pivot = array[i++%$];
>   // from is base-0, to is base-1.
>   int from = 0, to = array.length;
>   while (from != to) {
>     if (array[from] >= pivot && array[to-1] < pivot)
>       swap(array[from], array[to-1]);
>     if (array[from] < pivot)
>       from ++;
>     if (array[to-1] >= pivot)
>       to --;
>   }
>   array[0 .. from].qsort();
>   array[from .. $].qsort();
> }

It could be better.  I have a quicksort implementation that could probably beat it, but I haven't compared the two yet.  The existing one is a lot simpler though.



More information about the Digitalmars-d mailing list