插入排序(折半插入排序)
折半插入排序
1 #include<iostream> 2 #include <cstdlib> 3 4 using namespace std; 5 6 void BInsertSort(int *a, int l) 7 { 8 for (int i = 1;i < l; ++i) 9 { 10 int tmp = a[i]; 11 int low = 0,high = i-1; 12 while(low<=high) 13 { 14 int m = (low+high+1)/2; 15 if(tmp < a[m]) 16 { 17 high = m-1; 18 } 19 else 20 { 21 low = m + 1; 22 } 23 } 24 25 /*移动元素*/ 26 for(int j = i-1;j>high;j--) 27 { 28 a[j+1] = a[j]; 29 } 30 31 a[high+1] = tmp; 32 } 33 } 34 35 int main(int argc, char const *argv[]) 36 { 37 int a[] = {38,65,97,76,13,27,49}; 38 int l = sizeof(a)/sizeof(a[1]); 39 40 BInsertSort(a,l); 41 for (int i = 0; i < l; ++i) 42 { 43 cout<<a[i]<<" "; 44 } 45 return 0; 46 }