希尔排序——简单选择排序

2019-06-29
基本思想.PNG

排序过程.PNG

希尔排序过程.gif

复杂度.PNG

ShellCode.PNG

ShellSort.PNG

算法分析.PNG

希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。

希尔排序.png

1.首先确定分的组数:l e n g t h 2 \frac{length}{2}2length
2.然后对组中的元素进行插入排序;
3.然后继续将 l e n g t h 2 \frac{length}{2}2length,重复第一二步,直到 length = 0为止。

/*
 * @Date 2019/8/7 0:35
 * @Description 
 * 1.首先确定分的组数:length / 2;
 * 2.然后对组中的元素进行插入排序;
 * 3.然后继续将 length / 2,重复第一二步,直到 length = 0为止。
 **/

public class ShellSort {
    public void shellSort(int[] a) {
        int d = a.length;
        while (d != 0) {
            d = d / 2;//分的组数
            for (int x = 0; x < d; x++) {
                //对每组分别进行直接插入排序
                for (int i = x + d; i < a.length; i += d) {
                    int j = i - d;//j为同一组中要插入的数的前一个数
                    int tmp = a[i];//要插入的数
                    while (j >= 0 && a[j] > tmp) {
                        a[j + d] = a[j];
                        j = j - d;
                    }
                    a[j + d] = tmp;
                }
            }
        }
        System.out.println(Arrays.toString(a));
    }

    @Test
    public void testShellSort() {
        int[] a = {35, 11, 24, 52, 77, 69, 8, 3, 6, 62};
        int[] b = {7, 9, 3, 2, 5, 8, 6};
        shellSort(a);
        shellSort(b);
    }
}
/*
Output:
[3, 6, 8, 11, 24, 35, 52, 62, 69, 77]
[2, 3, 5, 6, 7, 8, 9]
 */

版权声明:本文为butbabuc原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。