插入排序

本文介绍了一种简单的排序算法——插入排序,并提供了详细的C++实现代码。通过实例演示了如何使用插入排序对整型数组进行升序排列。

  插入排序:

  1 #include <iostream>
  2 using namespace std;                                                        
  3 
  4 void swap(int &num1, int &num2)
  5 {
  6     int temp = num1;
  7     num1 = num2;
  8     num2 = temp;
  9 }   
 10 
 11 void insert_sort(int *arry, int p, int r)
 12 {
 13     //p和r为数组的下标
 14     int h = p + 1; //第一个数不用比较
 15     int t = r + 1; 
 16     while(h != t)
 17     {
 18         for(int i = 0; i < h; ++i)
 19         {
 20             if(arry[i] > arry[h])
 21             {
 22                 swap(arry[i], arry[h]);
 23             }   
 24         }   
 25         ++h;
 26     }   
 27 }   
 28 
 29 int main(int argc, const char *argv[])
 30 {
 31     int arry[5] = {23, 32, 1, 4, 16};
 32     for(auto &item: arry){ 
 33             cout << item << " ";
 34     }       
 35     cout << endl;
 36     insert_sort(arry, 0, 4);
 37     for(auto &item: arry){
 38             cout << item << " ";
 39     }       
 40     cout << endl;
 41     return 0;
 42 }   

 

转载于:https://www.cnblogs.com/bigshowxin/p/4376454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值