1. ## qsort problem (ish)

Well I was reading up on function pointers - all very interesting - and the example it showed me was the use of the qsort function. So, I closed the page, opened my IDE and fiddled. The result:

Code:

#include <algorithm>
#include <iostream>
int Comparison (const void* _a, const void* _b)
{
const int a = (const int) _a;
const int b = (const int) _b;
if (a > b)
return 1;
else {
if (a == b)
return 0;
else
return -1; // a < b
}
}
void walk_array (int a[], int length)
{
for (int i=0; i<length; i++)
std::cout << a[i] << std::endl;
}

int main()
{
int data[10] = { 3, 7, 5, 9, 11, 90, 44, 12, 54, 47 };
qsort ((void*) data, 10, sizeof (int), &Comparison);
walk_array (data, 10);
return 0;
}
It compiles and runs fine, I just get this output, apparently sorted, but not in any particular order. Weird:

Code:

90
3
5
9
11
7
44
12
54
47
Very unsorted.

2. Ah I just noticed something. Is my compare function returning the wrong number(s)?

3. The numbers are fine, your casting is a bit off. Plus you need to leave out the & operator when passing the function as an argument.

Code:
#include <algorithm>
#include <iostream>

int Comparison (const void* _a, const void* _b)
{
const int a = *((const int*)_a);
const int b = *((const int*)_b);

if (a > b) return 1;

if (a == b) return 0;

return -1; // a < b

}
void walk_array (int a[], int length)
{
for (int i=0; i<length; i++)
{
std::cout << a[i] << std::endl;
}
}

int main()
{
int data[10] = { 3, 7, 5, 9, 11, 90, 44, 12, 54, 47 };

qsort( data, 10, sizeof(data[0]), Comparison );

walk_array( data, 10 );

return 0;
}

4. Thanks that did the job!

Oh and thanks for clearing up my Comparison function; it was a little messy.