JAVA希尔排序(SHELL-SORT)

public class ShellSort {
    public static void sort(int[] array) {
        if (null == array||array.length<2){
            return;
        }
        sort(array, 0, array.length - 1);
    }

    private static void sort(int[] array, int start, int end) {
        for (int step = initialStep(end - start + 1); step >= 1; step = (step + 1) / 2 - 1) {
            for (int groupIndex = 0; groupIndex < step; groupIndex++) {
                insertSort(array, groupIndex, step, end);
            }
        }
    }

    private static int initialStep(int length) {
        int step = 1;
        while ((step + 1) * 2 - 1 < length - 1) {
            step = (step + 1) * 2 - 1;
        }
        return step;
    }

    private static void insertSort(int[] array, int groupIndex, int step, int end) {
        int endIndex = groupIndex;
        while ((endIndex + step) <= end) {
            endIndex += step;
        }
        for (int i = groupIndex + step; i <= end; i += step) {
            for (int j = groupIndex; j < i; j += step) {
                int insertedElem = array[i];
                if (array[j] > insertedElem) {
                    for (int k = i - step; k >= j; k -= step) {
                        array[k + step] = array[k];
                    }
                    array[j] = insertedElem;
                    break;
                }
            }
        }
    }
}

你可能感兴趣的:(JAVA希尔排序(SHELL-SORT))