造轮子博客链接
我对插入排序的理解
由于之前对于排序算法 当时学的那叫一个迷迷糊糊
但是现在重新学了一遍 又觉得豁然开朗
于是还是打算把自己的想法记录下来
这个插入算法的思想
就是对于一个数组
每次都抽一个数 然后插入到已经排序好的数组里面去 这个样子又会形成一个新的排序好的数组
不断的抽一个数(抽的顺序就是原来数组的顺序) 直到整个原来的数组都被抽完 全部被插入到排序好的数组中
未优化和优化的区别就在于
一个是用了swap 一个是没有用swap 访问空间加了倍
swap利用一个额外的空间储存数据 然后进行了两次数据赋值
而没有用swap的 只是把数据更大的向前移了一位 一次数据赋值
换种说法来说 swap的理解就好像是 已经把我们要插入的数据 放了进去 再进行排序 而不用swap只是向前移位的操作就像是 把我们要插入的数据一直捏在手上 知道找到自己的位置才放进去
代码实现(未改良版)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int temp;
vector<int> unsorted_vector;
cout<<"please input ur unsorted_list ~ '-1' is the stop symbol"<<endl;
while(cin>>temp)
{
if(temp == -1) break;
unsorted_vector.push_back(temp);
}
int v_size = unsorted_vector.size();
for(int i=1;i<v_size;++i)
{
for(int j=i;j>0 && unsorted_vector[j-1] > unsorted_vector[j];--j)
swap(unsorted_vector[j],unsorted_vector[j-1]);
}
cout<<"this is the sorted_vector numbers"<<endl;
for(const auto& num:unsorted_vector)
cout<<num<<' ';
return 0;
}
代码实现(改良版)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int temp,i,j;
vector<int> unsorted_vector;
cout<<"please input ur unsorted_list ~ '-1' is the stop symbol"<<endl;
while(cin>>temp)
{
if(temp == -1) break;
unsorted_vector.push_back(temp);
}
int v_size = unsorted_vector.size();
for(i=1;i<v_size;++i)
{
int temp = unsorted_vector[i];
for(j=i;j>0 && unsorted_vector[j-1] > temp;--j)
unsorted_vector[j] = unsorted_vector[j-1];
unsorted_vector[j] = temp;
}
cout<<"this is the sorted_vector numbers"<<endl;
for(const auto& num:unsorted_vector)
cout<<num<<' ';
return 0;
}
测试用例
15 175 128 1 126 19 20 181 80 35 39 104 194 184 93 8 64 188 24 112 173 160 2 189 13 85 30 6 125 63