C Reference function qsort()

The function qsort() of the stdlib.h is used to sort the elements of an array.

Usage of qsort():

void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );

The function qsort() sorts the num element of the array pointed by base. Every element has a size of size bytes long. The qsort function will use the comparator function to determine the order of the elements.

The function will not return a value. The content is modified in the newly sorted order.


The base parameter is a pointer to the first element of the array. The num parameter is the number of elements in the array. The size parameter gives the size in bytes of each element in the array.
The comparator function is a function that compares two elements. In most cases the function will follow the following prototype:

int comparator ( const void * element1, const void * element2 );

The function accepts two parameters which are pointers to the elements. These are type-casted as void*.

Return value:


Source code example of abort():


	int my_array[] = { 10, 5, 25, 15, 20, 30 };

	int comparetor (const void * a, const void * b)
		return ( *(int*)a - *(int*)b );

	int main ()
		int i;
		qsort (my_array, 6, sizeof(int), comparetor );

		for (i=0; i<6; i++)
			printf ("%d ",my_array[i]);
		return 0;

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.