首页 > 编程语言 > 详细

Java Shell排序

时间:2019-06-24 12:43:48      阅读:89      评论:0      收藏:0      [点我收藏+]

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

 

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

 

 

Java Shell排序

原文:https://www.cnblogs.com/Latiny/p/11076167.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!