c++二分插入排序
基本思想:
? ? ? ?二分法插入排序的思想和直接插入排序一樣,只是找位置插入的方式不同。這里按二分法找到合適位置,可減少比較次數(shù)。
示例:
? ? ? ?有6個記錄,前5個已拍好的基礎(chǔ)上,對第6個記錄排序。
?
?
?c++代碼如下:
#include<iostream> #include<stdlib.h> #include<time.h> using namespace std;void BinaryInsertSort(int *a,int n) {int i;for( i=0; i<10; i++) {int low=0;int high=i-1;int temp=a[i];int mid=0;while(low<=high) {mid=(low+high)/2;if(a[mid]<temp) {low=mid+1;} else {high=mid-1;}}int j;for(j=i-1; j>=low; j--) {a[j+1]=a[j];}if(i!=low)a[low]=temp;} } int* Random() {srand((unsigned) time(NULL));int *a=new int[10];for(int i=0; i<10; i++) {a[i]=rand()%10;cout<<a[i]<<" ";}cout<<endl;return a; } int main() {int *a=Random();BinaryInsertSort(a,10);for(int i=0; i<10; i++)cout<<a[i]<<" ";cout<<endl;return 0; }直接插入排序見:
直接插入排序
總結(jié)
- 上一篇: 多层装饰器、带参数装饰器
- 下一篇: 排序算法-C++实现