返回首页 C++ 模板

插入排序模板

将元素插入已排序部分的正确位置——对近乎有序的数据高效

插入排序 排序 GESP4
#include <bits/stdc++.h>
using namespace std;

int main() {
    int a[] = {5, 3, 8, 1, 2};
    int n = 5;

    // 插入排序
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }

    for (int x : a) cout << x << " ";  // 1 2 3 5 8
    cout << endl;

    return 0;
}

📖 要点说明

⚠️ 常见错误