# Sorting by Inbuilt Functions in C

For competitive coding purposes, writing sorting code can be messy, full of bugs, and redundant.  There is no need of writing sorting algorithms because the most efficient of them are already implemented.

In C,Inbuilt QuickSort is availabe in <stdlib.h> under the signature

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));

Where
base                 = void pointer towards the array to be sorted,
nitems            = number of elements in the array to be sorted
function ptr   = pointer towards a function returning an int by comparing two values.

The function type casts void pointer to required data type and returns the difference between values.

int cmpfunc (const void * p1, const void * p2)
{
return ( *(int*)p1 - *(int*)p2 );
}

If cmpfunc returns:

• < 0 The element pointed by p1 goes before the element pointed by p2
• = 0 The element pointed by p1 is equivalent to the element pointed by p2
• > 0 The element pointed by p1 goes after the element pointed by p2

This comparator function can be used to sort structures and unions also where one has to specify which data member of by what criteria comparison between two structure variable will be done!

Eg.

#include <stdio.h>;
#include <stdlib.h>;

int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}

void main(){
int arr[] = {6,5,9,8,2,1,0,69,47,58,25,11,66,23}, i;
qsort(arr,sizeof(arr),sizeof(arr[0]),cmpfunc);
for(i=0;i<sizeof(arr);i++)
printf("%d\n",arr[i]);
}

Output of this code is

0
1
2
5
6
8
9
11
23
25
47

“The most important property of a program is whether it accomplishes the intention of its user.”

C.A.R. Hoare

Keep Coding
Manish M Berwani