希尔排序

import java.util.Arrays;

public class My {
    void shellSort(int[] arr) {
        int n=arr.length;
        //当gap=1时,就是直接插入排序
        for (int gap = n / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < n; i++) {
                int temp = arr[i];
                int j;
                for (j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > temp) {
                        arr[j + gap] = arr[j];
                    } else {
                        break;
                    }
                }
                arr[j + gap] = temp;
            }
        }
    }

    public static void main(String[] args) {
        My my = new My();
        int[] arr = {5, 6, 1, 2, 4, 7, 2, 3, 4, 6, 4};
        my.shellSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

 

你可能感兴趣的:(希尔排序)