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

03 例题讲解

csharp
#include <iostream>
#include <vector>
using namespace std;
void insertionSort(vector<int>& arr) {
int n = arr.size();
for (int i = 1; i < n; i++) {
// 选择arr[i]作为要插入的元素
int key = arr[i];
// 将arr[i]与前面的元素比较后插入正确的位置
int j = i - 1;
// 将大于key的元素向后移动
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// 插入key
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;
}