package com.zsx.algorithm.sort;
import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {1, 3, 8, 4, 20, 5, 7, -1, 2, 24};
System.out.println("初始数据:" + Arrays.toString(arr));
System.out.println();
ShellSort shellSort = new ShellSort();
shellSort.sort(arr);
System.out.println();
System.out.println("最终结果:" + Arrays.toString(arr));
}
public void sort(int[] arr) {
for (int gap = arr.length / 2; gap > 0; gap = gap / 2) {
for (int i = gap; i < arr.length; i++) {
for (int j = i - gap; j >= 0; j = j - gap) {
if (arr[j] > arr[j + gap]) {
int temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
}
}
}
}
}
}
结果:
初始数据:[1, 3, 8, 4, 20, 5, 7, -1, 2, 24]
最终结果:[-1, 1, 2, 3, 4, 5, 7, 8, 20, 24]