折半插入排序


#include <iostream>

using namespace std;

const int N = 10;
int data[] = {6,1,2,7,9,3,4,5,10,8};

void binaryInsertSort(int* data,int n);
void printArray(int* data, int n);
int locate(int*data,int i);
int main()
{
    binaryInsertSort(data,N);
    printArray(data,N);
    return 0;
}

void binaryInsertSort(int* data,int n)
{
    int i,j,location,temp;
    for(i=1;i<n;++i)
    {

        location = locate(data,i);//先找到位置,再插入
        temp = data[i];
        for(j=i-1;j>=location;--j)
        {

            data[j+1] = data[j];
        }
        data[location] = temp;
    }
}

void printArray(int* data, int n)
{
    for(int i=0;i<n;++i)
    {
        cout<<data[i]<<"\t";
    }
    cout<<endl;
}
int locate(int*data,int i)
{
    int low = 0;
    int high = i-1;
    int mid = 0;
    while(low<=high)
    {
        mid = (low+high)/2;
        if(data[i]==data[mid]) return mid+1;
        else if(data[i]>data[mid]) low = mid+1;
        else if(data[i]<data[mid]) high = mid-1;
    }
    return low;
}
posted @ 2016-05-12 19:56  岳麓丹枫  阅读(132)  评论(0编辑  收藏  举报