Binary insertion sort (Binary Insert Sort)

Binary insertion sort

Ideas Analysis: Through direct insertion sort algorithm thinking, we can know the insertion sort insertion sequence first need to find the appropriate location for the insertion element to be inserted. By binary ((low + high) / 2 = mid) manner, with a mid to make us by way of binary insertion region, shrinking region inserted until low when high, we can find the insertion position of the element of high> +1. In this way the time complexity and direct insertion sort algorithm is still in the same level, but the use of a binary way, so when looking at the insertion position for the insert elements will be more efficient (especially when large amount of data).

Time complexity: (the entire reverse sequence) worst case time complexity of O (n- 2 ), the optimal situation (the entire sequence of the original order, when descending) time complexity is O (nlog 2 n-), where the average The time complexity is O (n- 2 ).

Source:

void BinaryInsertSort(int R[],int n)
{
    int i,j,low,mid,high,temp;
    for(i=1;i<n;i++)
    {
        low=0;
        high=i-1;
        temp=R[i];
        while(low<=high)    //找到合适的插入位置high+1,如果中间位置元素比要插入元素大,则查找区域向低半区移动,否则向高半区移动
        {
            mid=(low+high)/2;
            if(R[mid]>temp)
            {
                high=mid-1;
            }
            else
            {
                low=mid+1;
            }
        }
        for(j=i-1;j>=high+1;j--)    //high+1后的元素后移
        {
            R[j+1]=R[j];
        }
        R[j+1]=temp;    //将元素插入到指定位置
    }
}

Guess you like

Origin www.cnblogs.com/sunnylux/p/11039412.html