插入排序

  插入排序:

  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 }   

 

posted @ 2015-03-29 21:44  bigshowxin  阅读(110)  评论(0编辑  收藏  举报