C stdlib qsort() 函式
示例
對陣列進行排序
// Comparing function:
// Returns a positive number if a is greater than b
// Returns a negative number if a is less than b
// Returns 0 if a is equal to b
int compare(const void *a, const void *b) {
int *valA = a;
int *valB = b;
return *valA - *valB;
}
int main() {
// Create an array
int myArray[] = {20, 32, 5, 2, 24, 15};
int size = sizeof(myArray) / sizeof(myArray[0]);
// Sort the values in the array
qsort (myArray, size, sizeof(myArray[0]), compare);
// Display the values of the array
for(int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
自己動手試一試 »
定義和用法
qsort()
函式將陣列中的元素從最少到最多進行排序。
qsort()
函式定義在 `<stdlib.h>
` 標頭檔案中。
語法
qsort(void * arr, size_t amount, size_t size, compare);
size_t
資料型別是一個非負整數。
引數值
引數 | 描述 |
---|---|
arr | 必需。指定要排序的陣列。 |
amount | 必需。指定陣列中元素的數量。 |
大小 | 必需。以位元組為單位指定陣列中元素的長度。 |
比較 | 必需。指定一個函式,用於比較陣列中的一對元素,以確定哪個更大。 該函式應具有結構 int myFunction(const void * a, const void * b) ,其中引數 a 和 b 是正在比較的陣列元素的指標。如果 a 大於 b,該函式應返回正數;如果 a 小於 b,則返回負數;如果 a 等於 b,則返回零。 |