二分插入排序

#include <iostream>
#include<string>
using namespace std;
int main() {
    int a[10] = {19,8,10,34,12,45,90,44,5,22};
    int temp;
    int high, low, mid;
    int n = sizeof(a)/sizeof(int);
    cout << n;
    for (int i = 1; i < n; i++)
    {
        temp = a[i];
        high = i - 1;
        low = 0;
        while (low <= high)
        {
            mid = low + (high - low) / 2;
            if (temp>a[mid])
                low = mid + 1;
            else
                high = mid - 1;
        }
        for (int j = i ; j >low; j--)
        {
            a[j] = a[j - 1];
        }
        a[low] = temp;

    }
    for (int i = 0; i < n; i++)
        cout << a[i]<<" ";
    return 0;

}

减少元素之间比较次数

最坏情况o(n^2):

最好情况o(nlogn):刚好插入位置为二分位置

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/80632251