
01 插入排序的思想
02 插入排序的实现

03 例题讲解

#include <iostream>
#include <vector>
using namespace std;
void insertionSort(vector<int>& arr) {
int n = 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 = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cin >> n;
vector<int> treasures(n);
for (int i = 0; i < n; i++) {
cin >> treasures[i];
}
insertionSort(treasures);
for (int i = 0; i < n; i++) {
cout << treasures[i] << (i < n - 1 ? " " : "\n");
}
return 0;
}