返回首页 C++ 模板

快速排序算法模板

选基准分区——平均最快的排序算法

快速排序 排序 分区 GESP5
#include <bits/stdc++.h>
using namespace std;

void quickSort(int a[], int lo, int hi) {
    if (lo >= hi) return;
    int pivot = a[lo + (hi - lo) / 2];  // 选中间元素作基准
    int i = lo, j = hi;
    while (i <= j) {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j) { swap(a[i], a[j]); i++; j--; }
    }
    if (lo < j) quickSort(a, lo, j);
    if (i < hi) quickSort(a, i, hi);
}

int main() {
    int a[] = {5, 3, 8, 1, 2, 7, 4, 6};
    quickSort(a, 0, 7);
    for (int x : a) cout << x << " ";  // 1 2 3 4 5 6 7 8
    return 0;
}

📖 要点说明

⚠️ 常见错误