1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 //随机初始化数组 6 void fill(int *a,int n) 7 { 8 time_t ts; 9 unsigned int num = time(&ts); 10 srand(num); 11 for (int i = 0; i < n; i++) 12 { 13 a[i] = rand() % 100; 14 } 15 } 16 17 //输出数组内容 18 void print(int *a, int n) 19 { 20 for (int i = 0; i < n; i++) 21 { 22 printf("%4d", a[i]); 23 } 24 } 25 26 //比较,如果等于返回0,大于返回1,小于返回-1 27 int compare(const void *p1, const void *p2) 28 { 29 const int *pint1 = p1;//指针的类型转换 30 const int *pint2 = p2; 31 32 if (*pint1 == *pint2) 33 { 34 return 0; 35 } 36 else if (*pint1 > *pint2) 37 { 38 return 1; 39 } 40 else 41 { 42 return -1; 43 } 44 } 45 46 void main() 47 { 48 int a[100]; 49 //初始化数组 50 fill(a, 100); 51 //快速排序 52 qsort(a, 100, sizeof(int), compare); 53 //打印出结果 54 print(a,100); 55 56 system("pause"); 57 }