小滕的博客

小滕的技术点滴

java实现希尔排序

6 months ago · 0 MIN READ

希尔排序是插入排序的升级版,主要是减少插入排序的数组搬移次数,代码如下:

package com.xiaoteng;

import java.util.Arrays;

public class ShellSort {

    public int[] sort(int[] a) {
        int size = a.length / 2;
        while (size != 0) {
            for (int i = size; i < a.length; i++) {
                int tmp = a[i];
                int k = i - size;
                while (k >= 0 && tmp < a[k]) {
                    // 后移
                    a[k + size]  = a[k];
                    k -= size;
                }
                a[k + size] = tmp;
            }
            size /= 2;
        }
        return a;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 3, 18, 1, 999, 3, 19, 99, 29, 190, 120, 12};
        ShellSort shellSort = new ShellSort();
        System.out.println("排序结果:" + Arrays.toString(shellSort.sort(arr)));
    }
}

输出结果:

排序结果:[1, 1, 1, 2, 3, 3, 12, 18, 19, 29, 99, 120, 190, 999]

···

xiao teng



备案号:皖ICP备14012032号-5