1. 程式人生 > >拆半插入(二分法插入)——BinarySort

拆半插入(二分法插入)——BinarySort

 

package sort.com;
public class BinarySort {
    /**
     * 程式入口方法
     *    拆半插入(二分法拆入)相當於將原來的資料序列從中間一分為二,利用中間的索引
     *                 改變左右序列的索引值,一直進行到找到合適的插入位置


     */

 

    public static void main(String[] args) {

 

 

        int [] a = {8,2,-3,-15,21,0,99,-124};
        for(int i=1; i < a.length; i++){
            //將要排序的資料元素進行儲存
            int temp=a[i];
            //定義左,右兩個索引
            int leftIndex = 0;
            int rightIndex = i-1;
            //判斷左右索引是否滿足條件
            while(leftIndex<=rightIndex){
                //定義一箇中間的索引,用來動態的修改左右索引的值
                int midIndex=(leftIndex + rightIndex) / 2;
                //判斷將要插入的資料元素與已經排序的元素序列的中間值進行比較
                if(temp > a[midIndex]){
                    //若要插入的新元素較大,更新左索引
                    leftIndex = midIndex + 1;
                }
                //若要插入的新元素較小,更新右索引
                else{
                    rightIndex = midIndex - 1;
                }
                //輸出每次的midIndex值
                System.out.println("minIndex值為:"+ midIndex );
                
            }
                //用j來做已經排序後的資料序列中的最後一個數據元素的索引
                for(int j = i-1; j >= leftIndex;j--){
                    //進行移位操作
                    a[j+1] = a[j];
                }
                //插入資料元素
                a[leftIndex] = temp;
            }
        //遍歷並輸出陣列
        for(int v : a){
            System.out.print(v+",");
        }

    }

}