希尔排序

希尔排序

package org.study.order;

import java.util.Arrays;

public class ShellSort02 {

    public static void main(String[] args) {
        int[] arr = {9, 6, 11, 3, 5, 12, 8, 7, 10, 15, 14, 4, 1, 13, 2, 0};
        shellSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void shellSort(int[] arr) {
        //生成gap间隔
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            //先写一个插入排序
            for (int i = gap; i < arr.length; i ++) {
                for (int j = i; j >= gap; j -= gap) {
                    if (arr[j] < arr[j - gap]) {
                        swap(arr, j, j - gap);
                    }
                }
            }
        }

    }
    public static void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }
}


posted @ 2021-03-06 22:58  Leo-Wong  阅读(21)  评论(0编辑  收藏  举报