Take the 2-minute tour ×

Is there any library function available in C standard library to do sort?

share|improve this question
@Alexandru, the whole point of SO is to be a place for all programming-related question, of any skill level. Where do you think Google should direct people to when they use that query of yours? The powers that be want it to come here - when SO is the top Google link for that query, our job is done. –  paxdiablo Nov 25 '09 at 0:04
My original code was lazy and probably alot different then what you would have found with a Google search. However after all of the community input you have an example of a good implementation of how to use qsort. –  rerun Nov 25 '09 at 1:59
@paxdiablo: if that's the case, they might as well simply host the standard lib documentation - I doubt this question will add anything above that canonical reference, here. For some complex cases, perhaps - but just to find a basic function? –  Eamon Nerbonne Nov 25 '09 at 8:56
Even questions like this contribute to the eventual completeness of SO as a helpful database for stuck coders. –  littlegreen Jan 22 '10 at 4:49
Also in many cases people don't know what to search for. If you know that c has a sort function named qsort() documentation is easily accessible, however if you don't know what to look for what resource should one use. –  rerun Jan 28 '10 at 19:50

7 Answers 7

qsort() is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.

It does its magic and your array is sorted in-place. An example follows:

#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2) 
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
int main(int argc, char* argv[]) 
    int x[] = {4,5,2,3,1,0,9,8,6,7};

    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);

        printf ("%d ", x[i]);

    return 0;
share|improve this answer
You really should use sizeof(*x) in case you ever change the type in future but +1 for providing a sample. –  paxdiablo Nov 24 '09 at 5:54
In general case, an attempt to compare ints by subtracting one from another will result in overflow. It's better to stay away from that bad habit from the very beginning. Use return (f > s) - (f < s); –  AndreyT Nov 24 '09 at 6:32
You might also use sizeof(x) / sizeof(x[0]) in case your array size ever changes. You might also abstract that away into a macro, and you might change the declaration to x[] = so that the size can change without breaking your code. And for the final pedantry, you should never use an int to index arrays - that's what size_t is invented for. –  Chris Lutz Nov 24 '09 at 6:45
Okay, changed as per most suggestions. I draw the line, @ChrisL, at needing size_t since my arrays never get that big :-) And, @AndreyT, clever though that hack is, I prefer my code to be readable :-) –  paxdiablo Nov 24 '09 at 11:44
@paxdiablo: That "hack" is a well-established idiom. Any programmer worth his salt recognizes it immediately. It has no negative effects on readability. –  AndreyT Nov 24 '09 at 15:09

C/C++ standard library <stdlib.h> contains qsort function.

This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:


The only thing that you need to implement is the compare_function, which takes in two arguments of type "const void", which can be cast to appropriate data structure, and then return one of these three values:

  • negative, if a should be before b
  • 0, if a equal to b
  • positive, if a should be after b

1. Comparing a list of integers:

simply cast a and b to integers if x < y,x-y is negative, x == y, x-y = 0, x > y, x-y is positive x-y is a shortcut way to do it :) reverse *x - *y to *y - *x for sorting in decreasing/reverse order

int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;

2. Comparing a list of strings:

For comparing string, you need strcmp function inside <string.h> lib. strcmp will by default return -ve,0,ve appropriately... to sort in reverse order, just reverse the sign returned by strcmp

#include <string.h>
return (strcmp((char *)a,(char *)b));

3. Comparing floating point numbers:

double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;

4. Comparing records based on a key:

Sometimes you need to sort a more complex stuffs, such as record. Here is the simplest way to do it using qsort library.

typedef struct {
int key;
double value;
} the_record;

the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
share|improve this answer
A pretty good answer, but the explanation of the return value of the compare function is backwards. Also, in some of the examples, you're doing the x-y trick, which can give faulty results (and is less obvious than a simple comparison). –  Adrian McCarthy Nov 24 '09 at 16:37
Well,as far as I am concerned now .. this works for every contest ;) –  whacko__Cracko Nov 24 '09 at 22:53

For sure: qsort() is an implementation of a sort (not necessarily quicksort as its name might suggest).

Try man 3 qsort or have a read at http://linux.die.net/man/3/qsort

share|improve this answer
qsort does not have to be implemented using Quicksort. –  James McNellis Nov 24 '09 at 5:34

try qsort in stdlib.h.

share|improve this answer

Use qsort() in stdlib.

@paxdiablo The qsort() function conforms to ISO/IEC 9899:1990 (``ISO C90'').

share|improve this answer

There are several C sorting functions available in stdlib.h. You can do man 3 qsort on a unix machine to get a listing of them but they include:

  • heapsort
  • quicksort
  • mergesort
share|improve this answer
heapsort and mergesort are not in the standard. –  Technowise Nov 24 '09 at 5:34
Neither is quicksort. The standard does not mandate which algorithm is used. –  paxdiablo Nov 24 '09 at 5:51
They are on OSX at least. –  dj2 Nov 24 '09 at 5:55

While not in the standard library exactly, https://github.com/swenson/sort has just two header files you can include to get access to a wide range of incredibly fast sorting routings, like so:

#define SORT_NAME int64
#define SORT_TYPE int64_t
#define SORT_CMP(x, y) ((x) - (y))
#include "sort.h"
/* You now have access to int64_quick_sort, int64_tim_sort, etc., e.g., */
int64_quick_sort(arr, 128); /* Assumes you have some int *arr or int arr[128]; */

This should be at least twice as fast as the standard library qsort, since it doesn't use function pointers, and has many other sorting algorithm options to choose from.

It's in C89, so should work in basically every C compiler.

share|improve this answer

Your Answer


