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
size                  = sizeof(“Your DataType“)
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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s