排序之希尔排序

package ShellSort;

import chooseSort.Example;

/**
 * 希尔排序
 * 思想:插入排序的变步长扩展版。以h..1为步长,将数组分为若干组,然后进行插入排序
 * 解决了插入排序交换次数过多的问题。
 */
public class ShellSort extends Example {

    @Override
    public void sort(Comparable[] a) {
        int h = 1;
        int n = a.length;
        while(h<n/3) h=h*3+1;  //h<n+1
        while(h>=1){  //遍历所有步长,最后一次步长为1
            //步长为h的插入排序
            for(int i=h;i<n;i++){
                for(int j=i;j>h-1&&less(a[j],a[j-h]);j-=h){
                    exch(a,j,j-h);
                }
            }
            h=h/3;
        }
    }

//    /**
//     * 测试用例
//     * @param args
//     */
//    public static void main(String[] args) {
//        Integer[] a = new Integer[]{34,2,5,4,45,6,22};
//        ShellSort sort = new ShellSort();
//        sort.sort(a);
//        show(a);
//        System.out.println(isSorted(a));
//    }
}

 

posted @ 2019-06-20 15:18  由走啦啦啦  阅读(92)  评论(0编辑  收藏  举报