排序之二分查找插入排序算法

对于序列中第二个数开始,使用二分法查找其插入的位置,代码中最后low的值即为该数所在的位置,

注意跳出循环的条件为low > high,不能取等号

为保证为稳定的排序,if(a[mid]==x) low =mid + 1;

#include<iostream>
using namespace std;
int a[100];
void sort1(int *a, int n);
int main()
{
    int n;
    while(cin >> n)
    {
        for(int i = 0; i < n; i++)
           cin >> a[i];
        sort1(a, n);
        for(int i = 0; i < n; i++)
           cout <<"  " << a[i];
        cout << endl;
    }
}

void sort1(int *a, int n)
{
    for(int i = 1; i < n; i++)
    {
        int x = a[i];
        int low = 0;
        int high = i - 1;
        while(low <= high)
        {
            int mid = (low + high) / 2;
            if(x < a[mid])
               high = mid - 1;
            else
               low = mid + 1; 
        }
        for(int j = i - 1; j >= low; j--)
           a[j + 1] = a[j];
        a[low] = x;
    }
}

 

posted @ 2018-02-04 12:50  hui666  阅读(199)  评论(0)    收藏  举报