?
? ????? PHP ??? ???? ??? ?? ??
在頭文件<stdlib.h>中定義 | ||
---|---|---|
void qsort(void * ptr,size_t count,size_t size,int(* comp)(const void *,const void *)); | (1) | |
errno_t qsort_s(void * ptr,rsize_t count,rsize_t size,int(* comp)(const void *,const void *,void *),void * context); | (2) | (自C11以來) |
1)按照升序對ptr指向的給定數組進行排序。 該數組包含大小字節(jié)的計數元素。 由comp指向的函數用于對象比較。
2)與(1)相同,只是context
傳遞附加的上下文參數,comp
并且在運行時檢測到以下錯誤并調用當前安裝的約束處理函數:
count
或size
大于RSIZE_MAX
ptr
或comp
是一個空指針(除非count
是零)
與所有邊界檢查函數一樣,只有當__STDC_LIB_EXT1__由實現定義并且在包含stdlib.h之前用戶將__STDC_WANT_LIB_EXT1__定義為整數常量1時,qsort_s才能保證可用。
如果comp
表示兩個元素是等價的,則它們在結果排序數組中的順序是未定義的。
PTR | - | 指向要排序的數組的指針 |
---|---|---|
count | - | 數組中元素的個數 |
size | - | 數組中每個元素的大?。ㄒ宰止?jié)為單位) |
comp | - | 比較函數,如果第一個參數小于第二個參數,則返回負整數值;如果第一個參數大于第二個參數,則返回正整數值;如果參數相等,則返回零。比較函數的簽名應該等同于以下內容:int cmp(const void * a,const void * b); 該函數不得修改傳遞給它的對象,并且在調用相同對象時必須返回一致的結果,而不管它們在數組中的位置。 |
context | - | 附加信息(例如,整理順序),作為第三個參數傳遞給comp |
1) (none)
2)成功時為零,如果檢測到運行時約束違規(guī),則為非零
盡管有這個名字,C和POSIX標準都不需要使用快速排序來實現此功能,也不需要任何復雜性或穩(wěn)定性保證。
與其他邊界檢查函數不同,qsort_s
不會將零大小的數組視為運行時約束沖突,而是在不更改數組的情況下成功返回(另一個接受零大小數組的函數bsearch_s
)。
直到qsort_s
,qsort
的用戶經常使用的全局變量傳遞附加的上下文的比較功能。
#include <stdio.h>#include <stdlib.h>#include <limits.h> int compare_ints(const void* a, const void* b){ int arg1 = *(const int*)a; int arg2 = *(const int*)b; if (arg1 < arg2) return -1; if (arg1 > arg2) return 1; return 0; // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)} int main(void){ int ints[] = { -2, 99, 0, -743, 2, INT_MIN, 4 }; int size = sizeof ints / sizeof *ints; qsort(ints, size, sizeof(int), compare_ints); for (int i = 0; i < size; i++) { printf("%d ", ints[i]); } printf("\n");}
輸出:
-2147483648 -743 -2 0 2 4 99
C11標準(ISO / IEC 9899:2011):
7.22.5.2 qsort 函數(p:355-356)
K.3.6.3.2 qsort_s函數(p:609)
C99標準(ISO / IEC 9899:1999):
7.20.5.2 qsort 函數(p:319)
C89 / C90標準(ISO / IEC 9899:1990):
4.10.5.2 qsort 函數
bsearchbsearch_s(C11) | 在數組中搜索未指定類型的元素(函數) |
---|
| 用于qsort的C ++文檔 |