The qsort() function uses a comparison function to decide which element is smaller/greater than the other.
void qsort (void* base, size_t num, size_t size, int (*compare)(const void*,const void*));
The function is defined in <cstdlib> header file.
The qsort() function sorts the given array pointed by base in ascending order. The array contains num
elements, each of size bytes.
The function pointed by compare is used to compare two elements of the array. This function modifies the content of the array itself in the ascending order.
However, if two or more elements are equal, their order is undefined.
The prototype of the comparison function looks like:
int compare(const void* a, const void* b);
The qsort() function does not return anything. The sorted array is pointed to by base.
#include <iostream>
#include <cstdlib>
using namespace std;
int compare(const void* a, const void* b)
{
const int* x = (int*) a;
const int* y = (int*) b;
if (*x > *y)
return 1;
else if (*x < *y)
return -1;
return 0;
}
int main()
{
const int num = 10;
int arr[num] = {9,4,19,2,7,9,5,15,23,3};
cout << "Before sorting" << endl;
for (int i=0; i<num; i++)
cout << arr[i] << " ";
qsort(arr,num,sizeof(int),compare);
cout << endl << endl;
cout << "After sorting" << endl;
for (int i=0; i<num; i++)
cout << arr[i] << " ";
return 0;
}
When you run the program, the output will be:
Before sorting 9 4 19 2 7 9 5 15 23 3 After sorting 2 3 4 5 7 9 9 15 19 23