【算法基础】插入排序

1.排序

1.1 插入排序

  • 时间复杂度:O(n)~O(n*n)

  • 空间复杂度:O(1)

  • 稳定

  • 步骤:

1.设第一个元素为有序列。

2.取有序列后面的一个元素。

3.将该元素插入到有序列中的正确位置。

4.依次重复3、4步,直到完成排序。

#include<iostream>
usingnamespacestd;
​
//插入升序
voidinsert_sort_asc(int*arr, intn)
{
     for (inti=0; i<n-1; i++)
     {
          intend=i;//有序列的最后一个元素
          inttemp=arr[end+1];//当前需要插入排序的元素
​
          while (end>=0)//最坏情况下,遍历至有序列的第一个元素
          {
               if (temp<arr[end]) //待插入的数小,就将大数往后移
               {
                    arr[end+1] =arr[end];//后移
                    end--;//向前继续找位置
               }
               else
               {
                    break;//temp更大,则找到要插入的位置,退出循环
               }
          }
          arr[end+1] =temp;//temp插在较小数后
     }
}
​
//插入降序
voidinsert_sort_dec(int*arr, intn)
{
     for (inti=0; i<n-1; i++)
     {
          intend=i;
          inttemp=arr[end+1];
          while (end>=0)
          {
               if (temp>arr[end])
               {
                    arr[end+1] =arr[end];
                    end--;
               }
               else
               {
                    break;
               }
          }
          arr[end+1] =temp;
     }
}
​
voidoutput(int*arr, intn)
{
     for (inti=0; i<n; i++)
     {
          cout<<arr[i] <<" ";
     }
     cout<<endl;
}
​
intmain()
{
     intn, arr[99],copy[99];
     cout<<"Number of inputs:";
     cin>>n;
     cout<<"Inputs array:";
     for (inti=0; i<n; i++)
     {
          cin>>arr[i];
     }
     memcpy(copy, arr, n*sizeof(int));
​
     insert_sort_asc(copy, n);
     output(copy, n);
     insert_sort_dec(arr, n);
     output(arr, n);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值