抓一把亂序的牌,從第二張開始,每拿一張就插入已整理好的手牌中適當位置——這就是插入排序的直覺邏輯。電腦雖需逐一比較移動,但極高速度讓過程瞬間完成。
i = 1 ~ n-1,array[i] 為待插入元素。j = i-1 向前掃描,將大於 temp 的元素右移。array[j] <= temp 位置,將 temp 放入 array[j+1]。array[0..i] 永遠保持有序(已排序子陣列)。#include <stdio.h>
#define SIZE 10
void insertion_sort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j]; // 右移
j--;
}
arr[j + 1] = temp; // 插入
}
}
int main() {
int a[SIZE] = {5,1,8,9,4,6,3,2,7,0};
insertion_sort(a, SIZE);
for (int i = 0; i < SIZE; i++) printf("%-5d", a[i]);
return 0;
}
for (int j = i - 1; j >= 0 && arr[j] > temp; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = temp;
| 情況 | 時間複雜度 | 比較次數 | 移動次數 |
|---|---|---|---|
| 最佳(已有序) | O(n) | n-1 | 0 |
| 最差(逆序) | O(n²) | n(n-1)/2 | n(n-1)/2 |
| 平均 | O(n²) | ~n²/4 | ~n²/4 |
教科書以陣列 {5, 2, 4, 6, 1, 3} 為例,逐輪展示 i、j、key 變化與元素右移過程,強調「已排序子陣列」不變量的維持。
arr[0] 設為最小值,省去 j >= 0 邊界檢查。插入排序以「人類直覺整理牌」為藍本,代碼簡潔、穩定、適應性強,是小規模或近乎有序資料的最佳選擇。掌握其不變量邏輯與邊界處理,是演算法入門的關鍵一課。