思想:
插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
从i=1开始往后遍历,对于每个数据记录为temp,从该数据向前探索若比temp大则后移,直至第一个比temp小的数据,将temp插入到这个数据之后。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 3 using namespace std; 4 5 void InsertSort(int* arr,int n) 6 { 7 int i,j,temp; 8 for(i=1;i<n;i++) 9 { 10 temp = arr[i]; 11 j = i - 1; 12 while(j>=0 && temp < arr[j]) 13 { 14 arr[j+1] = arr[j]; 15 j--; 16 } 17 arr[j+1] = temp; 18 } 19 } 20 21 int main() 22 { 23 int * arr; 24 int n; 25 cout<<"Input the arr length:"<<endl; 26 cin>>n; 27 arr = new int[n]; 28 cout<<"Input the arr elements:"<<endl; 29 for(int i=0;i<n;i++) 30 { 31 cin>>arr[i]; 32 } 33 InsertSort(arr,n); 34 cout<<"The outcome:"<<endl; 35 for(int i=0;i<n;i++) 36 cout<<arr[i]<<endl; 37 return 0; 38 } 39 40 /************ 41 稳定 42 最好情况:数组正序排列,每次第i个记录一进入内层循环就退出,只有外层的n-1次。 43 时间复杂度O(n)。 44 最差情况:数组逆序排列(正好与需要排列的顺序相反),每次第i个记录都要在内层循环中比较i次。 45 时间复杂度为O(n^2)。 46 平均情况:O(n^2)。 47 空间复杂度:一个临时变量O(1)。 48 插入排序适用于待排序元素较少的情况。如果数组已有序用插入排序也很合适。 49 **************/