前言
由于自己的记性一直不好,总是记不住c语言中的快速排序函数,于是自己写下博客来记录一下。
快速排序库函数
c语言中的快速排序库函数如下(注意:库函数是在stdlib.h头文件中):
qsort(arr,length,size_t,cmp),其中arr代表要排序的数组名,length代表数组的长度 ,size_t代表数组元素的大小,cmp定义为
如何比较的的函数,cmp函数可如下定义:
int Cmp(const void *a,const void *b){
return *(type *)a - *(type *)b;
}其中type代表元素的类型,如int,char等
此时代表函数为非递减排序,若是return*(type*)b-*(type*)a,则是代表非递增排序。
例子如下:
#include<stdio.h>
#include<stdlib.h>
int IntCmp(const void *a,const void *b){//非递减比较函数
return *(int *)a - *(int *)b;
}
int CharCmp(const void *a,const void *b){//非递减比较函数
return *(char *)a - *(char *)b;
}
int CharCmp1(const void *a,const void *b){//非递增比较函数
return *(char *)b - *(char *)a;
}
int IntCmp1(const void *a,const void *b){//非增比较函数
return *(char *)b - *(char *)a;
}
int main(void)
{
int a[10] = {0, 6, 3, 1, 7, 5, 8, 9, 2, 4};
qsort(a, 10, sizeof(int), IntCmp);
//非递减排序
for (int i = 0; i < 10;i++){
printf("%d\t", a[i]);
}
printf("\n");
char b[10] = {'v', 'f', 'd', 'r', 't', 'y', 'e', 's', 'e', 'w'};
qsort(b, 10, sizeof(char), CharCmp);
//非递减排序
for (int i = 0; i < 10;i++){
printf("%c\t", b[i]);
}
printf("\n");
qsort(a, 10, sizeof(int), IntCmp1);
//非递增排序
for (int i = 0; i < 10;i++){
printf("%d\t", a[i]);
}
printf("\n");
qsort(b, 10, sizeof(char), CharCmp1);
//非递增排序
for (int i = 0; i < 10;i++){
printf("%c\t", b[i]);
}
getchar();
getchar();
return 0;
}
结果如下