Sorting an Array

torhu fake at address.dude
Wed Jul 11 16:27:41 PDT 2007


torhu wrote:
> okibi wrote:
>> This does seem like the best way, but I'm not sure how I would go about implement Quicksort into that code. Could you please give me some pointers?
> 
> I often use C's quicksort, found in std.c.stdlib.
> 
> void sort(T)(T[] array, bool function(T a, T b) compare) {
> 
>      // wrap compare in a C function
>      static extern(C) int cmp(void* a, void* b) {
>          return compare(*cast(T*)a, *cast(T*)b);
>      }
> 
>      qsort(array.ptr, array.length, array[0].sizeof, &cmp);
> }
> 
> compare has to return a negative number if a is smaller, positive is b 
> is smaller, or zero if they are equal.

Someone pointed out that this example doesn't work, since cmp can't 
access sort's arguments directly.  So I had to fix it.  cmp could 
obviously call compare through a local, static pointer, but for 
performance reasons I made qsort call the comparison function directly. 
  A quick test showed that this matters a whole lot in this case.


This code is tested, no worries.
---
import std.c.stdlib;
import std.stdio;


extern (C) void sort(T)(T[] array, int function(T* a, T* b) compare)
{
	alias extern (C) int function (void* a, void* b) ftype;

	qsort(array.ptr, array.length, array[0].sizeof, cast(ftype)compare);
}


extern(C) int compareInts(int* a, int* b) {
		return *a - *b;
}


void main()
{
	int[] a = [3, 14, 1];

	a.sort(&compareInts);

	writefln(a);  // prints '[1,3,14]'
}
---


More information about the Digitalmars-d-learn mailing list