125

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

5
  • 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, 2009 at 0:04
  • 1
    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, 2009 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? Nov 25, 2009 at 8:56
  • 4
    Even questions like this contribute to the eventual completeness of SO as a helpful database for stuck coders. Jan 22, 2010 at 4:49
  • 8
    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, 2010 at 19:50

9 Answers 9

147

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;
}
16
  • 6
    You really should use sizeof(*x) in case you ever change the type in future but +1 for providing a sample.
    – paxdiablo
    Nov 24, 2009 at 5:54
  • 18
    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); Nov 24, 2009 at 6:32
  • 4
    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, 2009 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. Nov 24, 2009 at 15:09
  • 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." Nov 27, 2018 at 16:41
69

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
  • 2
    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). Nov 24, 2009 at 16:37
  • Well,as far as I am concerned now .. this works for every contest ;) Nov 24, 2009 at 22:53
  • 6
    The 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, 2015 at 11:26
  • 2
    As 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)); }. Nov 24, 2017 at 7:28
  • 1
    For 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. Nov 24, 2017 at 7:33
11

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

1
  • 7
    qsort does not have to be implemented using Quicksort. Nov 24, 2009 at 5:34
8

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.

5

try qsort in stdlib.h.

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

4

Use qsort() in <stdlib.h>.

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

3

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
2
  • 7
    heapsort and mergesort are not in the standard.
    – Technowise
    Nov 24, 2009 at 5:34
  • 4
    Neither is quicksort. The standard does not mandate which algorithm is used.
    – paxdiablo
    Nov 24, 2009 at 5:51
0

GNU qsort source in stdlib shows that it is quicksort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.