I am a beginner to C and I am trying to understand the comparison function needed for the qsort function.
Part One: Syntax
A simple suggested use is this (I have included some main() code to print the results as well):
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25, 12, 13, 10, 40 };
int compare(const void *a, const void *b)
{
const int *ia = (const int *)a; // casting pointer types
const int *ib = (const int *)b;
return *ia - *ib;
}
int main()
{
int n;
for (n=0; n<10; n++)
{
printf("%d ",values[n]);
}
printf("
");
qsort(values, 10, sizeof(int), compare);
for (n=0; n<10; n++)
{
printf("%d ",values[n]);
}
printf("
");
system("pause");
return 0;
}
I don't understand why you need all the extra things in the compare function so I simplified it to this:
int compare (int *a, int *b)
{
return *a-*b;
}
This still works, and produces the same results. Can anyone explain to me what I removed, and why it still works?
Part Two: Why Pointers?
Additionally, do I really need to use pointers? Why can't I just compare "a" and "b" directly like so (this does NOT work):
int compare (int a, int b)
{
return a-b;
}
For some reason, with a multidimensional array, I was able to get away with NOT using pointers and for some reason it worked! What is going on? (Example code of sorting a multidimensional array by the 2nd item in each sub array):
#include <stdio.h>
#include <stdlib.h>
int values[7][3] = { {40,55}, {10,52}, {100,8}, {90,90}, {20,91}, {25,24} };
int compare(int a[2], int b[2])
{
return a[1] - b[1];
}
int main()
{
int n;
for (n=0; n<6; n++)
{
printf("%d,",values[n][0]);
printf("%d ",values[n][1]);
}
printf("
");
qsort(values, 6, sizeof(int)*3, compare);
for (n=0; n<6; n++)
{
printf("%d,",values[n][0]);
printf("%d ",values[n][1]);
}
printf("
");
system("pause");
return 0;
}
I am really glad the multidimensional array sorting is working as that is my end goal anyway, but I have no idea how I managed to get it to work (other than dumb luck and chopping up the code) so I would really love some explanation as to why some of the examples I provided work, and why some don't!
See Question&Answers more detail:
os