The standard C / C ++ library <stdlib.h> contains the qsort function.
This is not the best quicksort in the world, but it is fast and VERY EASY to use ... formal qsort syntax:
qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);
The only thing you need to implement is compare_function, which takes two arguments of type "const void" that can be assigned to the corresponding data structure, and then return one of these three values:
- negative if a should be before b
- 0 if a is equal to b
- positive if a should be after b
1. Comparison of the list of integers :
just add a and b to integers if x < y , xy negative, x == y , xy = 0 , x > y , xy is positive xy is a quick way to do this :) reverse *x - *y to *y - *x to sort in descending / reverse order
int compare_function(const void *a,const void *b) { int *x = (int *) a; int *y = (int *) b; return *x - *y; }
2. Comparison of the list of lines :
To compare a string, you need the strcmp function inside the <string.h> lib. strcmp will by default return -ve, 0, ve appropriately ... sort in reverse order, just undo the character returned by strcmp
3. Comparison of floating point numbers :
int compare_function(const void *a,const void *b) { double *x = (double *) a; double *y = (double *) b;
4. Comparison of key-based entries :
Sometimes you need to sort more complex things like recording. Here is the easiest way to do this using the 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; }