07-27-2023, 10:28 AM
I have read that the comparison function required by `qsort()` needs to have 3 outcomes:
* a negative result if `val1 < val2`
* `0` if `val1 == val2`
* a positive result if `val1 > val2`
As far as I know, sorting an array only requires a predicate that returns true or false. Take bubble sort for example:
int compare(int a, int b)
{
if(a>b) return 1;
return 0;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if ( compare(arr[j],arr[j+1]) )
swap(&arr[j], &arr[j+1]);
}
So why does the `qsort()` comparison function need to have 3 possible outcomes and not 2?
* a negative result if `val1 < val2`
* `0` if `val1 == val2`
* a positive result if `val1 > val2`
As far as I know, sorting an array only requires a predicate that returns true or false. Take bubble sort for example:
int compare(int a, int b)
{
if(a>b) return 1;
return 0;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if ( compare(arr[j],arr[j+1]) )
swap(&arr[j], &arr[j+1]);
}
So why does the `qsort()` comparison function need to have 3 possible outcomes and not 2?