C++ qsort()

The qsort() function uses a comparison function to decide which element is smaller/greater than the other.

qsort() prototype

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.


qsort() Parameters

  • base: Pointer to the first element of the array to sort
  • num: Number of element in the array
  • size: Size in bytes of each element in the array
  • compare: A pointer to a function that that compares two elements. It returns
    • a negative integer if the first argument is less than the second
    • a positive integer if the first argument is greater than the second
    • zero if both arguments are equal

The prototype of the comparison function looks like:

int compare(const void* a, const void* b);

qsort() Return value

The qsort() function does not return anything. The sorted array is pointed to by base.


Example : How qsort() function works?

#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
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges