c++二分插入排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/82806967

基本思想:

       二分法插入排序的思想和直接插入排序一样,只是找位置插入的方式不同。这里按二分法找到合适位置,可减少比较次数。

示例:

       有6个记录,前5个已拍好的基础上,对第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;
}

直接插入排序见:

直接插入排序

猜你喜欢

转载自blog.csdn.net/qq_39993896/article/details/82806967