I have got a 2d array and I would like to quicksort it with the given qsort() function in C++:
unsigned work[N][3];
I would like to sort the “work” array by the third index… so if work[i] goes before work[j] if work[i][2]>work[j][2].
I know I would need to use a function to compare it, but I have no inkling how to do that.
edit:
If I would do the following, would that help:
unsigned work[3][N];
qsort(work[2], N, sizeof(unsigned), compare);
And compare would be the following:
int compare(const void* a, const void* b)
{
return(*(unsigned*)a-*(unsigned*)b);
}
?
Well, the short answer would be to not use
std::qsortat all, butstd::sort. But unfortunately the latter won’t work, sinceunsigned int[3]is not assignable. So here’s the easieststd::qsortsolution.First we define a custom comparator function:
Which we then use to sort the array. Keep in mind that
workis an array of arrays, and thuswork[0]is an array of 3unsigned ints, there’s no pointer indirection involved in any way. So it’s perfectly suited for being sorted bystd::qsort:By the way, the third element is indexed with
2, since we usually start to count at0in C++ (and many other programming languages).EDIT: Though, the best solution would indeed be to drop this array of arrays and use something more suited to C++, like a
std::vectorofstd::array<unsigned int,3>s (or any other datastructure that fits a bit more to the actual context):Which can then be sorted with a simple:
Or, if you don’t have C++11 (though in this case you won’t have
std::arrayeither and need to start thinking about a resonable datastructure apart from a mere 3-array):As a bonus to much clearer code, you also most probably get a slight performance boost of
std::sortoverstd::qsort.