文章目錄
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
Sort elements of array
Sorts the num elements of the array pointed by base, each element size bytes long, using the comparator function to determine the order.
The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements of the array.
The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.
Parameters
-
base
-
Pointer to the first element of the array to be sorted.
-
num
-
Number of elements in the array pointed by
base.
-
size
-
Size in bytes of each element in the array.
-
comparator
-
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * elem1, const void * elem2 );
The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.
The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
Return Value
(none)
具體應用:
//都是升序的comparator,要降序只需要將*A和*B反過來即可 //1.comparator of int and its exampleint num[100];int cmp_int(const void* a, const void* b){int* A = (int*)a;int* B = (int*)b;return *A - *B;}qsort(num,100,sizeof(num[0]),cmp_int);//2.comparator of double and its exampledouble num[100];int cmp_double( const void* a , const void* b ) { double* A = (double*)a;double* B = (double*)b;return *A > *B ? 1 : -1; //a little different}qsort(num,100,sizeof(num[0]),cmp_double);//3.comparator of char and its examplechar ch[100];int cmp_char(const void* a, const void* b){char* A = (char*)a;char* B = (char*)b;return *A - *B;}qsort(ch,100,sizeof(ch[0]),cmp_char);//4.comparator of char string and its examplechar word[200][10]; int cmp_string(const void* a,const void* b){char* A = (char*)a;char* B = (char*)b;return strcmp(A, B);}//是針對字串數組按字典排序,非string類型 qsort(word,200,sizeof(word[0]),cmp_string);//將200個單詞按字典序排序 //5.結構體一級排序 struct In { double data; int other; }In s[100]; //按照data的值從小到大將結構體排序,若為其他類型可以參照基本類型comparator照葫蘆畫瓢 int cmp( const void *a ,const void *b) { In* A = (In*)a;In* B = (In*)b;return (*A).data > (*B).data ? 1 : -1; }qsort(s,100,sizeof(s[0]),cmp); //6.結構體二級排序struct In { int x; int y; }In s[100]; //按照x從小到大排序,當x相等時按照y從大到小排序int cmp( const void *a , const void *b ) { struct In *c = (In *)a; struct In *d = (In *)b; if(c.x != d.x) return c.x - d.x; else return d.y - c.y; }qsort(s,100,sizeof(s[0]),cmp);