qsort是C语言的函数,在“stdlib.h”头文件中;而sort是C++的函数,在<algorithm>头文件中。
两者的用法也有不同:
qsort:
功 能: 使用快速排序例程进行排序
功 能: 使用快速排序例程进行排序
头文件:stdlib.h
用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
参数: 1 待排序数组首地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的指针,用于确定排序的顺序
sort:
功 能: 使用快速排序例程进行排序
头文件:algorithm
sort:
功 能: 使用快速排序例程进行排序
头文件:algorithm
用法:void sort( RandomIt first, RandomIt last, Compare comp );
参数:1 待排序数组首地址
qsort例子:
参数:1 待排序数组首地址
2
待排序数组尾地址
3 用于确定排序顺序的比较函数
qsort相比sort用法上最大的不同在于比较函数上,qsort的比较函数必须是int (*fcmp)(const void *,const void *)这样的形式(留意其形参的类型),而sort的比较函数则没有这样的要求。
qsort例子:
对一维数组的排序实例(从小到大排序):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include<stdio.h>
#include<stdlib.h>
int
comp(
const
void
*a,
const
void
*b)
{
return
*(
int
*)a-*(
int
*)b;
}
int
main()
{
int
*array;
int
n;
scanf
(
"%d"
,&n);
array=(
int
*)
malloc
(n*
sizeof
(
int
));
int
i=0;
for
(;i<n;i++)
|