6 Java Shell排序

希尔排序是先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。

 

1、基本思想

将待排序数组按照步长gap进行分组,然后将每组的元素利用直接插入排序的方法进行排序;每次再将gap折半减小,循环上述操作;当gap=1时,利用直接插入,完成排序。

 

2、算法描述

①. 选择一个增量序列t1,t2,…, tk ,其中ti > tj,tk = 1;(一般初次取数组半长,之后每次再减半,直到增量为1)

②. 按增量序列个数k,对序列进行k 趟排序;

③. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。

 

3、代码实现

public class ShellSort {

    public static void main(String[] args) {
        Long startTime = System.currentTimeMillis();
        //int[] array = new int[]{10, 1, 9, 2, 8, 3, 7, 4, 6, 5};
        int[] array = new int[100000];
        for (int i = 0; i < 100000; i++) {
            array[i] = (int) (Math.random() * 100000);
        }
        shellSort(array);
        Long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }
    
    public static void shellSort(int[] array) {
        int len = array.length;
        int gap = len / 2;
        int i, j, tmp;
        while (gap >= 1) {
            for (i = gap; i < len; i++) {
                tmp = array[i];
                j = i - gap;
                while (j >= 0 && array[j] >= tmp) {
                    array[j + gap] = array[j];
                    j = j - gap;
                }
                j = j + gap;
                if (j != i) {
                    array[j] = tmp;
                }
            }
            //System.out.println(Arrays.toString(array));
            gap = gap / 2;
        }
    }
}
View Code

 

 

posted @ 2019-06-24 11:28  Latiny  阅读(181)  评论(0编辑  收藏  举报