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()
函數會在搜尋期間多次呼叫此函數。 此函數必須比較 key 與 元素 ,並傳回下列其中一個值:
Value | 意義 |
---|---|
小於 0 | key 小於 元素 |
0 | key 等於 元素 |
大於 0 | key 大於 元素 |
已排序的陣列元素會以遞增順序儲存,如 compare 函數所定義。 您可以透過在 比較中反轉「大於」及「小於」的感覺來以相反順序排序。 當兩個元素平均比較時,未指定元素的順序。
回覆值
此方法不會傳回任何值。
範例
此範例會使用範例中提供的 comparison 函數
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
*/