首页 > 代码库 > C++实现折半插入排序

C++实现折半插入排序

 1 # include<iostream> 2 # include<cstdio> 3 using namespace std; 4 void BinaryInsertSort(int *_piArr,int len) 5 { 6     int i = 1,j = 0; 7     int low = 0; 8     int high = 0; 9     int middle = 0;10     for(;i < len;i++)11     {12         if(_piArr[i] >= _piArr[i-1])13         {14             continue;15         }16         low = 0;17         high = i-1;18         j = i;19         int x = _piArr[i];20         while(low <= high)21         {22             middle = (low+high)/2;23             if(x < _piArr[middle])24             {25                 high = middle -1;26             }else if(x > _piArr[middle]){27                 low = middle + 1;28 29             }else{30                 break;31             }32         }33         while(j > low){34             _piArr[j] = _piArr[j-1];35             j--;36         }37         _piArr[low] = x;38     }39 }40 int main()41 {42         int a[100];43         int n;44         cin>>n;45         for(int i = 0;i < n;i++)46         {47             cin>>a[i];48         }49         BinaryInsertSort(a,n);50         for(int i = 0; i < n;i++)51         {52             cout<<a[i]<<" ";53         }54 }
View Code

 

C++实现折半插入排序