C 自帶了一個排序函數qsort, 使用時要定義一個compare方法。
下面是一個例子:
/* qsort example */ #include <stdio.h> /* printf */ #include <stdlib.h> /* qsort */ int values[] = { 40, 10, 100, 90, 20, 25 }; int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main () { int n; qsort (values, 6, sizeof(int), compare); for (n=0; n<6; n++) printf ("%d ",values[n]); return 0; }
假設有一個復雜類型的數組,要按照其中的某個屬性來排序時又該怎么做呢?
#include <stdlib.h> #include <stdio.h> typedef struct _block{ int att1; int att2; }Block; int compare(const void *a, const void *b) { int aa = ((Block *)a)->att1; int bb = ((Block *) b)->att1; if (aa > bb) return 1; else if (aa < bb) return -1; else return 0; } int main() { int n; Block b[3]; b[0].att1= 3; b[0].att2=3; b[1].att1 =8; b[1].att2=8; b[2].att1 = 5; b[2].att2=5; qsort(b, 3, sizeof(Block), compare); for (n=0; n<3; n++){ printf("%d %d\n", b[n].att1, b[n].att2); } return 0; }
要想按照降序排列,只需要修改compare函數的返回值就行了。