qsort ()- 排序数组
格式
#include <stdlib.h>
void qsort(void *base, size_t num, size_t width,
int(*compare)(const void *key, const void *element));语言级别
ANSI
线程安全
是
描述
qsort() 函数对 num 个元素的数组进行排序,每个元素的大小为 width 个字节。 base 指针是指向要排序的数组的指针。 qsort() 函数使用已排序的元素覆盖此数组。
Compare 自变量是一个指向您必须提供的函数的指针,该函数采用指向 key 自变量的指针,并按该顺序指向数组 元素。 qsort() 函数在搜索期间调用此函数一次或多次。 该函数必须比较 键 和 元素 ,并返回下列其中一个值:
| 值 | 含义 |
|---|---|
| 小于 0 | key 小于 元素 |
| 0 | 键 等于 元素 |
| 大于 0 | 键 大于 元素 |
已排序的数组元素按升序存储,如 比较 函数所定义。 您可以通过在 比较中反转 "大于" 和 "小于" 的含义来按反向顺序排序。 当两个元素进行平均比较时,未指定元素的顺序。
返回值
没有返回值。
示例
此示例使用示例中提供的比较函数
compare() 按升序对自变量 (argv) 进行排序。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Declaration of compare() as a function */
int compare(const void *, const void *);
int main (int argc, char *argv[ ])
{
int i;
argv++;
argc--;
qsort((char *)argv, argc, sizeof(char *), compare);
for (i = 0; i < argc; ++i)
printf("%s\n", argv[i]);
return 0;
}
int compare (const void *arg1, const void *arg2)
{
/* Compare all of both strings */
return(strcmp(*(char **)arg1, *(char **)arg2));
}
/*********** If the program is passed the arguments: ************
******** 'Does' 'this' 'really' 'sort' 'the' 'arguments' 'correctly?'****
**************** then the expected output is: *******************
arguments
correctly?
really
sort
the
this
Does
*/