Is there any library function available in C standard library to do sort?
-
25@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 00:04
-
1My 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 01: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 08:56
-
4Even questions like this contribute to the eventual completeness of SO as a helpful database for stuck coders. – littlegreen Jan 22 '10 at 04:49
-
8Also 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
9 Answers
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);
for (int i = 0 ; i < 10 ; i++)
printf ("%d ", x[i]);
return 0;
}

- 25,014
- 6
- 48
- 78
-
6You 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 05:54
-
-
19In 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);` – AnT stands with Russia Nov 24 '09 at 06:32
-
1You 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 06:45
-
I did write this as a quick example only but thank for the commentary non the less. – rerun Nov 24 '09 at 06:49
-
4Okay, 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
-
3@paxdiablo: That "hack" is a well-established idiom. Any programmer worth his salt recognizes it immediately. It has no negative effects on readability. – AnT stands with Russia Nov 24 '09 at 15:09
-
@paxdiablo :Only using sizeof(*x) won't work if you are changing the type, you have to modify the compare function accordingly. – whacko__Cracko Nov 24 '09 at 16:13
-
1There's nothing wrong with indexing arrays using `int` (or `char` for that matter). The *size* of an array, however, should be a `size_t`. – Stephen Canon Nov 24 '09 at 19:12
-
I wrote a very simple version of quicksort and the internal library one turned out to be slower – Confuse Nov 20 '16 at 04:52
-
1that's possible the standard library implementations are meant to solve general problems. If you have more information about a problem you can special case and always outperform. – rerun Nov 21 '16 at 17:32
-
1C doesn't support overloading so there's nothing wrong with the assumption that sizeof(*x) will always be int as you've already made it in the comp function. – Confuse Jun 07 '17 at 04:29
-
1
-
-
3@JAamish ISO C99 Standard N1256, in "7.20.5.2 The `qsort` function" Point 4 "If two elements compare as equal, their order in the resulting sorted array is unspecified." – 12431234123412341234123 Nov 27 '18 at 16:41
-
@12431234123412341234123 thanks for pointing to the spec.. :) It is very interesting and important point about qsort.. this really helps – J Aamish Nov 28 '18 at 07:33
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:
qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);
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>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}
3. Comparing floating point numbers:
int compare_function(const void *a,const void *b) {
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;
int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
}

- 6,592
- 8
- 33
- 35
-
2A 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
-
6The x-y trick doesn't work if the difference between x and y is greater than the largest representable int. So it is fine when comparing two positive numbers, but will fail comparing, eg, INT_MAX and -10. Upvoted though because I like all the examples of sorting very different types. – Douglas Jan 24 '15 at 11:26
-
2As well as the overflow problem in both the integer comparator and the key comparator functions, the string compare function is incorrect. When sorting an array of `int`, the values passed to the comparator are both `int *` disguised as `void *`. When sorting an array of `char *`, therefore, the values passed to the comparator are both `char **` disguised as `void *`. Therefore, the correct code needs to be: `int compare_function(const void *a,const void *b) { return (strcmp(*(char **)a, *(char **)b)); }`. – Jonathan Leffler Nov 24 '17 at 07:28
-
1For integer comparisons that are overflow resistant, consider `if (x > y) return +1; else if (x < y) return -1; else return 0;`, or if you want a simple expression, then `return (x > y) - (x < y);`. This always evaluates two comparisons at the C level, but the optimizer might be able to avoid that. Subtraction doesn't work on unsigned values. The first version works well when you are dealing with a series of comparison — comparing 2 integer members of a structure first, and if they're equal, then two doubles, then two strings, etc. There's more than one way to do it, in C as well as Perl. – Jonathan Leffler Nov 24 '17 at 07:33
-
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

- 69,862
- 18
- 95
- 117

- 4,526
- 1
- 22
- 25
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.

- 529
- 5
- 5
I think you are looking for qsort
.
qsort
function is the implementation of quicksort algorithm found in stdlib.h
in C/C++
.
Here is the syntax to call qsort
function:
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
List of arguments:
base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements
Here is a code example which uses qsort
to sort an array:
#include <stdio.h>
#include <stdlib.h>
int arr[] = { 33, 12, 6, 2, 76 };
// compare function, compares two elements
int compare (const void * num1, const void * num2) {
if(*(int*)num1 > *(int*)num2)
return 1;
else
return -1;
}
int main () {
int i;
printf("Before sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
// calling qsort
qsort(arr, 5, sizeof(int), compare);
printf("\nAfter sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
return 0;
}
You can type man 3 qsort
in Linux/Mac terminal to get a detailed info about qsort
.
Link to qsort man page

- 379
- 3
- 6
Use qsort()
in <stdlib.h>
.
@paxdiablo
The qsort()
function conforms to ISO/IEC 9899:1990 (``ISO C90'').

- 9,276
- 5
- 26
- 43

- 758
- 5
- 7
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

- 9,534
- 4
- 29
- 52
-
7
-
4Neither is quicksort. The standard does not mandate which algorithm is used. – paxdiablo Nov 24 '09 at 05:51