Tuesday, October 17, 2006

qsort-based template class for sorting arrays


template class CSortArray {
public:
static void Sort(T *a, int Size, bool Desc = FALSE) {
qsort(a, Size, sizeof(T), Desc ? CmpDesc : CmpAsc);
}

private:
static int CmpAsc(const void *arg1, const void *arg2) {
if (*(T *)arg1 < *(T *)arg2)
return(-1);
if (*(T *)arg1 > *(T *)arg2)
return(1);
return(0);
}
static int CmpDesc(const void *arg1, const void *arg2) {
if (*(T *)arg1 > *(T *)arg2)
return(-1);
if (*(T *)arg1 < *(T *)arg2)
return(1);
return(0);
}
};

1 comment:

kskzmus said...

Use std::sort instead.
CSortArray is equivalent to

std::sort(a, a + Size, less<T>()) for ascending or
std::sort(a, a + Size, greater<T>()) for descending.

qsort is slower than std::sort especially for the basic types such as int or byte, since qsort relies on the memory copy (memcpy possibly) in contrast to the structural copy (=) in std::sort.