插入排序步骤:
- 假设前面的序列已经有序
- 不断将后面待处理的数,插入前面有序的序列
- 重复1.2直到处理完所有数据
算法描述:
#include<bits/stdc++.h>
using namespace std;
void insertSort(vector<int> &src){
if(src.size() == 1) return;//处理只有一个元素的数组
for(int i = 1;i<src.size();++i){
int temp = src[i];
int j = i -1;
while(j>=0){
if(temp > src[j]) break;
src[j+1] = src[j];
--j;
}
src[j+1] = temp;
}
}
int main(){
vector<int> src({-3,-1,6,2,10,7,9});
insertSort(src);
copy(src.begin(),src.end(),ostream_iterator<int>(cout," "));
cout<<endl;
return 0;
}
/*
-3 -1 2 6 7 9 10
*/
另一版
class insert_{
public:
void insert_sort(vector<int> &data){
if(data.empty()) return;
int size = data.size();
for(int i = 1; i < size; ++i){
int tmp = data[i];
int j = i - 1;
while(j >= 0 && data[j] > tmp){ // 修改了此处
data[j + 1] = data[j];
--j;
}
data[j + 1] = tmp;
}
copy(data.begin(), data.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
};
分析原始数据与结果:
程序中的原始数组数据为{-3,-1,6,2,10,7,9},首先假设以-3为包含元素的数组有序,从-1开始往后的元素不断向-3对应的数组中插入,使得插入元素后变为有序。
- 从-1开始比较,先和-3比较,由于-3小于-1,所以不动,目前前面有数组变为{-3,-1}。
- 接着遍历到6,和-1比较,比-1大,所以也不用动,当前有序数组为{-3,-1,6}。
- 此时,遍历到2,和6比较,比6小,所以需要将6后移一位,以便为插入元素腾出位置,接着2和-1比较,比-1大,此时就将2插入到-1的后面空位置即可,继续处理下一个元素。
- 此时的原数组变为{-3,-1,2,610,7,9}。不断进行上述处理,最终数组会变为有序。
优化:
寻找在有序数组中插入的位置时,可以使用二分查找,进而优化时间复杂度。