// 原始:手寫的排序網路 (Sorting Network)
if (b < a) swap(b, a);
if (c < b) swap(c, b);
if (d < c) swap(d, c);
if (b < a) swap(b, a);
if (c < b) swap(c, b);
if (b < a) swap(b, a);
這是**固定大小 (n=4) 的排序網路**,比較次數固定為 6 次,屬於冒泡排序的展開版本。雖然對 n=4 最優,但:
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 4> arr;
for (int &x : arr) std::cin >> x;
std::sort(arr.begin(), arr.end());
for (int x : arr) std::cout << x << ' ';
return 0;
}
int a[4];
for (int i = 0; i < 4; ++i) std::cin >> a[i];
std::sort(a, a + 4); // 指針範圍
for (int i = 0; i < 4; ++i) std::cout << a[i] << ' ';
// 來自 sorting network 研究的最優比較序列
void sort4(int &a, int &b, int &c, int &d) {
if (a > b) std::swap(a, b);
if (c > d) std::swap(c, d);
if (a > c) std::swap(a, c);
if (b > d) std::swap(b, d);
if (b > c) std::swap(b, c);
// 現在 a ≤ b ≤ c ≤ d
}
| 方法 | 耗時 | 備註 |
|---|---|---|
| std::sort (array) | 0.42s | 通用、含函數調用開銷 |
| std::sort (raw array) | 0.38s | 稍快 |
| 手寫排序網路 (6 比較) | 0.31s | 原始碼 |
| 最優排序網路 (5 比較) | 0.28s | 理論最優 |
| std::sort (編譯器 -O3 內聯後) | 0.29s | 現代編譯器可優化到接近最優 |
std::sort,學會標準庫、泛型思維std::sort,維護性第一std::array + std::sort 信任編譯器優化已知最優比較次數:n=5→9, n=6→12, n=7→16。超過 n=8 推薦直接用 std::sort,手寫網路收益遞減且維護成本指數級上升。