← 回首頁

插入排序法 Insertion Sort

調整參數後按下「開始排序」,可選擇自動播放或分解模式逐步學習。

(5-50個)
中速
未排序
已排序
當前元素
比較中
移動中

C++ 插入排序法參考程式

Insertion Sort 會把每個新元素插入左側已排序區段,直到整個陣列完成排序。

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

void insertionSort(vector<int>& arr) {
    int n = static_cast<int>(arr.size());

    for (int i = 1; i < n; ++i) {
        int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            --j;
        }

        arr[j + 1] = key;
    }
}

int main() {
    vector<int> data = {12, 11, 13, 5, 6};

    insertionSort(data);

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

    return 0;
}