算法C++ 插入排序代码实现(第二章)


造轮子博客链接

算法第四版C++算法实现全集


我对插入排序的理解

由于之前对于排序算法 当时学的那叫一个迷迷糊糊
但是现在重新学了一遍 又觉得豁然开朗
于是还是打算把自己的想法记录下来

这个插入算法的思想
就是对于一个数组
每次都抽一个数 然后插入到已经排序好的数组里面去 这个样子又会形成一个新的排序好的数组

不断的抽一个数(抽的顺序就是原来数组的顺序) 直到整个原来的数组都被抽完 全部被插入到排序好的数组中

未优化和优化的区别就在于
一个是用了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


实现效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Love 6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值