插入排序:折半插入排序

折半插入排序

  百度百科:折半插入排序(binary insertion sort)是对插入排序算法的一种改进,由于排序算法过程中,就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列,这样我们不用按顺序依次寻找插入点,可以采用折半查找的方法来加快寻找插入点的速度。

示例代码:

    /**
     * 折半插入排序
     * @param array
     */
    public static void BInsertSort(int[] array){
        int i,j,temp,low,high,mid;
        for(i=1;i<array.length;++i){
            temp=array[i];
            low=0;high=i-1;
            while(low<=high){   //查找元素插入位置
                mid=(low+high)/2;
                if(temp<array[mid]){
                    high=mid-1;
                }else{
                    low=mid+1;
                }
            }
            for(j=i-1;j>=high+1;--j){ //移动元素(从尾开始,往后移动一位,直到插入位置为止)
                array[j+1]=array[j];
            }
            array[high+1]=temp;
            System.out.println(Arrays.toString(array));
        }
    }

示例结果:

 

posted @ 2020-04-23 13:29  Cool_Yang  阅读(306)  评论(0)    收藏  举报