插入排序就是将待排序的序列元素插入到已经完成排序的子序列中的合适的位置上。就像打扑克,假设我们手里的牌是5689,而下一张新摸的牌是7,则我们会被7插入到6和8之间的位置,构成一个顺子56789。(这个时候就有人说了“谁说的!我就是摸到什么牌都直接捏到手里,不会按照牌面去调整顺序”。嗯嗯,你说的都对,俺不抬杠,别打俺)。
算法思路
对于一个待排序序列,将序列中的第一个元素看作是原序列的一个有序子序列;然后从第二个元素开始向后遍历,将后续的每个元素插入到有序子序列中的适当位置。
算法过程
1、将待排序序列的第一个元素看做原序列的一个有序子序列,把第二个元素到最后一个元素当成是未排序的无序子序列;
2、从第二个元素开始向后遍历待排序的无序子序列;
3、将遍历到的元素插入到有序子序列中的适当位置(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)。
例如数组[14, 5, 86, 22, 6, 54, 30, 54, 29]:
1、把14看作已经有序的子序列,从5开始向后遍历;
2、5小于14,将5插入到14的前面,此时序列为[5, 14, 86, 22, 6, 54, 30, 54, 29],其中5和14构成有序子序列,其余元素为待操作的无序序列;
3、86大于14,不改变相对位置,此时序列为[5, 14, 86, 22, 6, 54, 30, 54, 29],其中[5, 14, 86]构成有序子序列,其余元素为待操作的无序序列;
3、重复上述步骤,得到最终的有序序列[5, 6, 14, 22, 29, 30, 54, 54, 86]。
代码实现
伪代码逻辑
InsertSort(array){
len=array.size();
for i from 1 to len{
index=i; //要插入的元素索引
tem=array[index]; //记录要插入的元素
//寻找元素要插入的位置
while(index>0 and array[index-1]>tem){
array[index]=array[index-1]; //满足条件的元素向前移动
index--;
}
if(index!=i){
array[index]=tem; //插入元素
}
}
}
c++代码函数实现
//插入排序
void InsertSort(vector<int>& arr) {
for(int i = 1; i < arr.size(); i++) {
int index = i;
int tem = arr[index];
while (index > 0 && arr[index - 1] > tem) {
arr[index] = arr[index - 1];
index--;
}
if (index != i) {
arr[index] = tem;
}
}
}
整体代码测试
#include <bits/stdc++.h>
using namespace std;
void InsertSort(vector<int>& arr) {
for(int i = 1; i < arr.size(); i++) {
int index = i;
int tem = arr[index];
while (index > 0 && arr[index - 1] > tem) {
arr[index] = arr[index - 1];
index--;
}
if (index != i) {
arr[index] = tem;
}
}
}
int main() {
vector<int> arr{ 14, 5, 86, 22, 6, 54, 30, 54, 29};
cout << "before sort: " << endl;
for (auto a : arr) {
cout << a << "\t";
}
cout << endl;
InsertSort(arr);
cout << "after sort: " << endl;
for (auto a : arr) {
cout << a << "\t";
}
cout << endl;
system("pause");
return 0;
}
output