插入排序之折半插入排序(java实现)

import java.util.Arrays;


public class BinaryInsertSort {

    public static void binaryInsertSort(DataWraper[] data){
        System.out.println("开始排序:");
        int arrayLength=data.length;
        for(int i=1;i<arrayLength;i++){
            DataWraper tmp=data[i];
            int low=0;
            int high=i-1;
            while(low<=high){
                //找出low、high的中间索引
                int mid=(low+high)/2;
                //如果tmp值大于low、high中间元素的值
                if(tmp.compareTo(data[mid])>0){
                    //限制在索引大于mid的那一半中搜索
                    low=mid+1;
                }else{
                    //限制在索引小于mid的那一半中搜索
                    high=mid-1;
                }
            }
            //将low到i处的所有元素向后整体移动一位
            for(int j=i;j>low;j--){
                data[j]=data[j-1];
            }
            data[low]=tmp;
            System.out.println(Arrays.toString(data));
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DataWraper [] data={
                new DataWraper(21, ""),
                new DataWraper(30, ""),
                new DataWraper(49, ""),
                new DataWraper(30, "*"),
                new DataWraper(16, ""),
                new DataWraper(9, ""),
               
        };
        System.out.println("排序之前:\n"+Arrays.toString(data));
        binaryInsertSort(data);
        System.out.println("排序之后:\n"+Arrays.toString(data));
    }

}

结果:

排序之前:
[21, 30, 49, 30*, 16, 9]
开始排序:
[21, 30, 49, 30*, 16, 9]
[21, 30, 49, 30*, 16, 9]
[21, 30*, 30, 49, 16, 9]
[16, 21, 30*, 30, 49, 9]
[9, 16, 21, 30*, 30, 49]
排序之后:
[9, 16, 21, 30*, 30, 49]

posted @ 2011-07-18 14:21  朱旭东  阅读(551)  评论(0编辑  收藏  举报