← 回首頁

快速排序法 Quick Sort

觀察 pivot 分區與遞迴流程,可使用自動播放或分解模式逐步學習。

(5-50個)
中速
未處理
目前分區
Pivot
比較中
交換中
已定位

C++ 快速排序法參考程式

快速排序透過「選 pivot + 分區」反覆把資料切成更小範圍,再遞迴完成排序。

C++
#include <iostream>
#include <vector>
using namespace std;

int partition(vector<int>& arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; ++j) {
        if (arr[j] <= pivot) {
            ++i;
            swap(arr[i], arr[j]);
        }
    }

    swap(arr[i + 1], arr[high]);
    return i + 1;
}

void quickSort(vector<int>& arr, int low, int high) {
    if (low >= high) {
        return;
    }

    int pi = partition(arr, low, high);
    quickSort(arr, low, pi - 1);
    quickSort(arr, pi + 1, high);
}

int main() {
    vector<int> data = {8, 3, 1, 7, 0, 10, 2};

    quickSort(data, 0, static_cast<int>(data.size()) - 1);

    cout << "排序結果: ";
    for (int x : data) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}