插入排序

一、原理:

  插入排序是在一个序列A[0, ..., n-1]中,将从第i位(i >= 2)开始,将第i位插入到前面已排好顺序的序列A[0,... ,i-1]中,最终得到一个有序序列。

二、代码:

 1 /*Sample Input:
 2   5
 3   3 4 5 1 2
 4 
 5   Sample Output:
 6   1 2 3 4 5
 7 */
 8 
 9 #include<bits/stdc++.h>
10 using namespace std;
11 
12 int main(int argc, char const *argv[])
13 {
14     int t;//序列的长度
15     while(cin >> t && t){
16         int arr[t];
17         for(int i = 0; i < t; i++)cin >> arr[i];
18 
19         for(int i = 1; i < t; i++){
20             int tmp = arr[i];
21             int j = i;
22             
23             while(j >= 1){
24                 if(arr[j-1] >= tmp){
25                     arr[j] = arr[j-1];
26                     j--;
27                 }
28                 else break;    
29             }
30             arr[j] = tmp;
31         }
32         for(int i = 0; i < t; i++)cout << arr[i] << ' ';
33         cout << endl;
34     }
35     return 0;
36 }

 三、分析  

   (1)最好的情况是O(n),即序列已经顺序排好的情况;

  (2)最坏的情况是O(n^2),即序列逆序排列的情况。

    //End

原文地址:https://www.cnblogs.com/Vincent-Bryan/p/5968533.html