- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - qsort() 函式
C 的stdlib 庫 qsort() 函式是一個排序函式,用於對陣列進行升序或降序排序。它被稱為快速排序。
此函式基於快速排序演算法,該演算法是最快速和最高效的排序演算法之一。
語法
以下是 qsort() 函式的 C 庫語法:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
引數
此函式接受以下引數:
base - 表示指向要排序的陣列第一個元素的指標。
nitems - 表示陣列中的元素個數。
size - 表示陣列中每個元素的大小。
compare - 表示指向比較函式的函式指標,該函式比較兩個元素。
返回值
此函式不返回任何值。
示例 1
在這個示例中,我們建立一個基本的 C 程式來演示 qsort() 函式的使用。
#include <stdio.h>
#include <stdlib.h>
// Comparison function
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {10, 5, 4, 6, 9};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("Following is the sorted array: ");
int i;
for (i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
以下是輸出:
Following is the sorted array: 4 5 6 9 10
示例 2
下面的 C 程式對陣列的字元進行排序。使用 qsort() 函式。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Comparison function
int compare(const void *arg1, const void *arg2){
return strcasecmp(*(const char **)arg1, *(const char **)arg2);
}
int main(void){
char *colors[] = {"B", "D", "A", "W", "Z", "X", "M", "O"};
int i;
// Size of the array
int size = sizeof(colors) / sizeof(colors[0]);
printf("Original array elements:\n");
for (i = 0; i < size; i++)
{
printf("%s ", colors[i]);
}
printf("\n\n");
// Use qsort to sort
qsort(colors, size, sizeof(char *), compare);
printf("Following is the sorted array: ");
for (i = 0; i < size; ++i)
{
printf("%s ", colors[i]);
}
return 0;
}
輸出
以下是輸出:
Original array elements: B D A W Z X M O Following is the sorted array: A B D M O W X Z
示例 3
讓我們再建立一個 C 程式來對陣列的字串進行排序。使用 qsort() 函式。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Comparison function
int compare(const void *arg1, const void *arg2){
return strcasecmp(*(const char **)arg1, *(const char **)arg2);
}
int main(void){
char *colors[] = {"Vivek", "Aman", "Shriansh", "Tapas"};
int i;
// Size of the array
int size = sizeof(colors) / sizeof(colors[0]);
printf("Original array elements:\n");
for (i = 0; i < size; i++)
{
printf("%s ", colors[i]);
}
printf("\n");
// Use qsort to sort
qsort(colors, size, sizeof(char *), compare);
printf("Following is the sorted array: ");
for (i = 0; i < size; ++i)
{
printf("%s ", colors[i]);
}
return 0;
}
輸出
以下是輸出:
Original array elements: Vivek Aman Shriansh Tapas Following is the sorted array: Aman Shriansh Tapas Vivek
廣告