C库中有自带的快排函数 qsort() ;
它的函数原型为:
void qsort(void * , size_t ,size_t size , int (__cdecl *)(const void *, const void *));
第一个参数是指向数组首地址的指针 ,第二个参数是数组大小 ,第三个参数是数组的类型大小 ,第四个参数是指向函数的指针。其中函数是一个比较函数,接收两个参数,比较大小;第一个参数小于第二个则返回一个负数 ;相等则返回0 ;大于则返回正数;
代码:
#include<stdio.h> #include<time.h> #include<stdlib.h> #define N 40 int mysort(const void *a, const void *b) { const int *a1 = (const int *)a; const int *b1 = (const int *)b; if(*a1 < *b1) return -1; else if(*a1 == *b1) return 0; else return 1; } int main() { int i,a,b; int array[N]; a=clock(); // 测试程序运行时间 srand((unsigned int)time(NULL)); for(i=0;i<N;i++) array[i]=rand()%100; printf("list: "); for(i=0;i<N;i++) printf("%d ",array[i]); putchar(' '); printf("there: "); for(i=0;i<N;i++) { qsort(array,N,sizeof(int),mysort); printf("%d ",array[i]); } b=clock(); // 运行结束 printf(" 运行时间:%.4f s ",(double)(b-a)/CLOCKS_PER_SEC);// 除以 CLOCKS_PER_SEC 然后再将类型转换为double return 0; }