Built in functions for sorting arrays in C

Check out qsort

Syntax:

#include <stdlib.h>
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

Description:

The qsort() function sorts buf (which contains num items, each of size size) using Quicksort. The compare function is used to compare the items in buf. compare should return negative if the first argument is less than the second, zero if they are equal, and positive if the first argument is greater than the second. qsort() sorts buf in ascending order.


You can use qsort in stdlib.h. It is quick-sort algorithm, which has average time complexity of O(nlogn) and worst case complexity of O(n2). The C99 standard and even the newer C11 Standard doesn't mandate the implementation or time complexity of the function. However, it is very likely that common implementation will use algorithm that yields average case O(nlogn) time complexity (which is optimal for sorting by comparison).

You can use this to sort any kind of array (even struct) - but you must provide a comparison function to compare between 2 elements of the array.


qsort is well known. There are others also like heapsort, mergesort etc. Please check the link for more details.

Please note that all of them take comparison functions as input, making them easily usable with native as well as user created data types.