tags:

views:

287

answers:

6

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

A: 

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
dj2
heapsort and mergesort are not in the standard.
Technowise
Neither is quicksort. The standard does not mandate which algorithm is used.
paxdiablo
They are on OSX at least.
dj2
+2  A: 

try qsort in stdlib.h.

Traveling Tech Guy
+5  A: 

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

McPherrinM
`qsort` does not have to be implemented using Quicksort.
James McNellis
+12  A: 

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;
}
rerun
You really should use sizeof(*x) in case you ever change the type in future but +1 for providing a sample.
paxdiablo
What is _tmain?
Thomas Padron-McCarthy
Good point, @Thomas, I got rid of that non-standard monstrosity :-)
paxdiablo
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
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
I did write this as a quick example only but thank for the commentary non the less.
rerun
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
@paxdiablo: That "hack" is a well-established idiom. Any programmer worth his salt recognizes it immediately. It has no negative effects on readability.
AndreyT
@paxdiablo :Only using sizeof(*x) won't work if you are changing the type, you have to modify the compare function accordingly.
nthrgeek
There'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
+2  A: 

Use qsort() in stdlib.

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

prime_number
+3  A: 

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;
}
nthrgeek
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
Well,as far as I am concerned now .. this works for every contest ;)
nthrgeek