本文提供四種經典排序算法的完整可運行 C 語言代碼,包含冒泡排序、選擇排序、快速排序和希爾排序。每個示例都包含主函數測試代碼,可直接編譯運行驗證效果。
採用雙層循環,外層控制輪數,內層進行相鄰元素比較交換。優化點:引入 noswap 標誌,若某輪無交換則提前結束。
#include <stdio.h>
#include <stdbool.h>
void sort(int array[], int size) {
int i, j, temp;
bool noswap;
for (i = 0; i < size - 1; i++) {
noswap = true;
for (j = i + 1; j < size; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
noswap = false;
}
}
if (noswap) break;
}
}
void main() {
int i;
int a[10] = {1, 33, 78, 34, 787, 213, 132, 35, 32, 21};
sort(a, 10);
for (i = 0; i < 10; i++)
printf("%6d", a[i]);
}
每輪從未排序部分選出最小元素,與未排序部分首元素交換。代碼簡潔,交換次數最少(最多 n-1 次)。
#include <stdio.h>
void sort(int array[], int size) {
int i, j, k, temp;
for (i = 0; i < size - 1; i++) {
k = i;
for (j = i + 1; j < size; j++) {
if (array[k] > array[j])
k = j;
}
temp = array[k];
array[k] = array[i];
array[i] = temp;
}
}
void main() {
int a[] = {12, 43, 54, 23, 32, 65, 87, 2, 34, 54};
int i;
sort(a, 10);
for (i = 0; i < 10; i++)
printf("%d ", a[i]);
}
採用遞歸分治策略,選取中間元素作為基準,雙指針從兩端向中間掃描交換,最後遞歸處理左右子數組。平均時間複雜度 O(n log n)。
#include <stdio.h>
void quick_sort(int array[], int first, int last) {
int temp, low, high, list_separator;
low = first;
high = last;
list_separator = array[(first + last) / 2];
do {
while (array[low] < list_separator) low++;
while (array[high] > list_separator) high--;
if (low <= high) {
temp = array[low];
array[low++] = array[high];
array[high--] = temp;
}
} while (low <= high);
if (first < high) quick_sort(array, first, high);
if (low < last) quick_sort(array, low, last);
}
void main() {
int a[9] = {12, 23, 34, 65, 93, 32, 21, 9, 8};
quick_sort(a, 0, 8);
for (int i = 0; i < 9; i++)
printf("%d ", a[i]);
printf("\n");
}
基於插入排序改進,引入增量序列(初始為 size/2,每次減半)。對每個增量分組進行插入排序,逐步縮小增量直到 1。
#include <stdio.h>
void shell_sort(int array[], int size) {
int temp, gap, i, flag;
gap = size / 2;
do {
do {
flag = 0;
for (i = 0; i < size - gap; i++) {
if (array[i] > array[i + gap]) {
temp = array[i];
array[i] = array[i + gap];
array[i + gap] = temp;
flag = 1;
}
}
} while (flag);
} while (gap = gap / 2);
}
void main() {
int array[] = {1, 2, 32, 43, 64, 7654, 321, 42, 23, 97, 56, 32, 78, 45, 32};
int i;
shell_sort(array, 15);
for (i = 0; i < 15; i++)
printf("%10d", array[i]);
}
實際工程中,C 標準庫的 qsort() 通常基於快速排序優化實現,建議優先使用庫函數;若需自定義比較邏輯或嵌入式環境無標準庫,上述代碼可作參考基礎。