之前,我们已经写过快速排序的程序,而在C语言的库函数中就有快速排序的库函数,即为qsort, 其用法如下:
#include <stdio.h> #include <stdlib.h> int compInc(const void *a, const void *b) { return *(int *)a - *(int *)b; } int compDec(const void *a, const void *b) { return *(int *)b - *(int *)a; } int main() { int a[5] = {11,2,13,4,7}; int b[5] = {11,2,13,4,7}; int len = 5; int i; printf("递增排序结果:\n"); qsort(a, len, sizeof(a[0]), compInc); for(i = 0; i < len; i ++) { printf("%d ", a[i]); } printf("\n\n"); printf("递减排序结果:\n"); qsort(b, len, sizeof(b[0]), compDec); for(i = 0; i < len; i ++) { printf("%d ", b[i]); } printf("\n"); return 0; }结果为:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define M 12 #define N 20 int compareInc(const void *a, const void *b) { return strlen((char *)a) - strlen((char*)b); } int compareDec(const void *a, const void *b) { return strlen((char *)b) - strlen((char*)a); } int main(void) { int i; char s[M][N]= { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; qsort(s, M, sizeof(char) * N, compareInc); for(i = 0;i < M; i++) printf("%s\n", s[i]); printf("\n"); qsort(s, M, sizeof(char) * N, compareDec); for(i = 0;i < M; i++) printf("%s\n", s[i]); return 0; }结果为:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define M 12 #define N 20 int compare1(const void *a, const void *b) { return *(char *)a - *(char*)b; } int compare2(const void *a, const void *b) { return *(char *)b - *(char*)a; } int main(void) { int i; char s[M][N]= { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; qsort(s, M, sizeof(char) * N, compare1); for(i = 0;i < M; i++) printf("%s\n", s[i]); printf("\n"); qsort(s, M, sizeof(char) * N, compare2); for(i = 0;i < M; i++) printf("%s\n", s[i]); return 0; }结果为:
#include <stdio.h> #include <stdlib.h> #define N 6 typedef struct { char name[15]; int score; }Student; int compare1(const void *a,const void *b) { return ((Student*)a)->score - ((Student*)b)->score; } int compare2(const void *a,const void *b) { return *(((Student*)a)->name) - *(((Student*)b)->name); } void print(Student s) { printf("%-15s : %d\n", s.name, s.score); } int main() { Student s[N] = { "Zhang San", 94, "Li Si", 80, "You", 94, "I", 100, "He", 72, "She", 60 }; int i; qsort(s, N, sizeof(Student), compare1); for(i = 0; i < N; i++) { print(s[i]); } printf("\n"); qsort(s, N, sizeof(Student), compare2); for(i = 0; i < N; i++) { print(s[i]); } return 0; }结果为: