Java希尔排序

希尔排序的思想是使数组中任意间隔为h的元素都是有序的。

对于任意以1结尾的h序列,我们都能够将数组排序。这就是希尔排序。

package sortTest;

/**
 * Created by Main on 2018/5/12.
 */
public class ShellSort {

    public static boolean less(Comparable a,Comparable b){
        return a.compareTo(b)<0;
    }

    public static void exchange(Comparable[] a,int i,int j){
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void shellSort(Comparable[] a){
        int len = a.length;
        int h = 1;
        while(h=1){
            for (int i = h; i < len ; i++) {
                for (int j = i; j >=h; j=j-h) {
                    if(less(a[j],a[j-h])){
                        exchange(a,j,j-h);
                    }
                }
            }
            h=h/3;
        }
    }

    public static void main(String[] args) {
        Integer[] numbers = new Integer[]{1,8,9,2,6,5,7};
        shellSort(numbers);
        for (Integer number: numbers) {
            System.out.print(number);
        }
    }
}

你可能感兴趣的:(java)