After writing so long to sort still feel most comfortable with ready-made. In fact, the C language in fact, with a quick sort stdlib library, but its function call interface is too complex, so daunting. In order to deepen their memories, so write this blog
First look at the function prototype
_CRTIMP void __cdecl qsort(void*, size_t, size_t, int (*)(const void*, const void*))
It looks very complicated in fact CRTIMP is just a macro definition (do not understand too much to complain)
its actual meaning is as follows
C - C Language
R - run run
TIM - time Hou
P - Parameter
__cdecl system is also predefined macros. (It seems to be supported, uncertain input parameters, such as printf, where it should not mean that the self-interest of your mother).
void return NULL, qsort function name.
Parentheses:
The first parameter is representative of the first address of any data type;
second parameter is representative of any data type of the space, i.e. the length;
third parameter is representative of the size of the data type;
fourth parameter ordering the most troublesome here, and we have to write a comparison function cmp (). 1 returns from small to large, -1 is returned, descending
theory do not speak too much, looking directly at how to use:
a: integer comparison
int num[100]; int cmp ( const void *a , const void *b ) { return *(int *)a > *(int *)b ? 1 : -1; } qsort(num,100,sizeof(num[0]),cmp);
Ministry of subtraction, fear of data overflow.
Two, Char type comparison
1 char word[100]; 2 3 int cmp( const void *a , const void *b ) 4 { 5 return *(char *)a > *(char *)b 1 ? -1; 6 } 7 8 qsort(word,100,sizeof(word[0]),cmp);
Third, the floating-point comparison
double in[100]; int cmp( const void *a , const void *b ) { return *(double *)a > *(double *)b ? 1 : -1; } qsort(in,100,sizeof(in[0]),cmp);
Fourth, the structure of Comparative
typedef double ElemtType struct In { ElemtTypedata; int other; }s[100]; int cmp( const void *a ,const void *b) { return (*(struct In *)a).data > (*(struct In *)b).data ? 1 : -1; } qsort(s,100,sizeof(s[0]),cmp);
Five, two sort of structure
struct the In { int x; int y; } S [ 100 ]; // accordance with small to large x, when x is equal descending order according to y int CMP ( const void * A, const void * B) { struct * C = the In ( struct the In * ) A; struct the In * D = ( struct the In * ) B; IF (! the C-> X = D-> X) return the C-> X - D-> X; the else return D -> Y - the C-> Y; } qsort (S, 100 ,sizeof(s[0]),cmp);
Sixth, sorting strings
struct the In { int Data; char str [ 100 ]; } S [ 100 ]; // sorted lexicographically in the structure of the string str int CMP ( const void * A, const void * B) { return strcmp ((* ( struct the In *) A) -> STR, (* ( struct the In *) B) -> STR); } qsort (S, 100 , the sizeof (S [ 0 ]), CMP);
Life is not easy, gentlemen encourage each other