思路
- 构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
- 选择排序相关博文:https://blog.csdn.net/weixin_42107311/article/details/105249526
- 冒泡排序相关博文:https://blog.csdn.net/weixin_42107311/article/details/105248680
伪代码
- 从第一个元素开始,该元素可以认为已经被排序;
- 取出下一个元素,在已经排序的元素序列中从后向前扫描;
- 如果该元素(已排序)大于新元素,将该元素移到下一位置;
- 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
- 将新元素插入到该位置后;
- 重复步骤2~5
![](https://img-blog.csdnimg.cn/20200402203559939.gif)
代码
#include <iostream>
using namespace std;
void InsertSort(int *list, int n);
int main(){
int list[] = {2,1,23,2,21,5,3,2};
int len = sizeof(list)/ sizeof(list[0])-1;
InsertSort(list, len);
for (int i = 0; i < len; ++i) {
cout << list[i] << ",";
}
return 0;
}
void InsertSort(int *list, int n) {
int preIndex, current;
for (int i = 1; i < n; ++i) {
preIndex = i-1; // 和要插入的数作比较的值
current = list[i]; // 插入的值
// i=2
while (preIndex >=0 && list[preIndex]> current){
list[preIndex +1 ] = list[preIndex];
preIndex--;
}
list[preIndex+1] = current;
}
}