八大排序算法之 一 插入排序---折半插入排序算法

public class BinaryInsertSort {
    public static void main(String[] args){
        int[] array = {2,6,1,9,4,3,23,65,0,7};
        System.out.print("the array before is:");
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i]+"   ");
        }
        System.out.println(" ");
        System.out.println("the array after is:");
        binaryInsertSort(array);
    }
    private static void binaryInsertSort(int[] array){
        int len = array.length;
        for(int i = 1; i < len; i++){
            int low = 0;
            int high = i - 1;
            int temp = array[i];
            while(low <= high){
                int middle = (low + high)/2;
                if(array[i] < array[middle]){
                    high = middle - 1;
                }else{
                    low = middle + 1;
                }    
            }                            
        for(int j = i;j > low; j--){
            array[j] = array[j-1];
        }
        array[low] = temp;
        for(int z = 0; z < array.length; z++){
            System.out.print(array[z]+"   ");
        }
        System.out.println(" ");
        }
    }
}

如图所示,是代码实现。

你可能感兴趣的:(插入排序)