package Sort;
import java.util.Arrays;
/**
* 希尔排序(Shellsort)也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序
* 希尔排序:非稳定排序算法
*
* */
public class ShellSort {
public static void main(String[] args) {
int[] arr = new int[]{8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
shellSort2(arr);
System.out.println(" " + Arrays.toString(arr));
}
public static void shellSort(int[] arr) {
int length = arr.length;
int temp;
for (int step = length / 2; step >= 1; step /= 2) { // 分组
for (int i = step; i < length; i++) { // 遍历各个组
temp = arr[i];
int j = i - step; // 找到组内的其他元素
while (j >= 0 && arr[j] > temp) {
arr[j + step] = arr[j];
j -= step;
}
arr[j + step] = temp;
}
}
}
public static void shellSort2(int[]arr){
for (int step = arr.length/2; step >=1 ; step/=2) { // 步长
//i:代表即将插入的元素角标,作为每一组比较数据的最后一个元素角标
//j:代表与i同一组的数组元素角标
for (int i = step; i < arr.length; i++) {
for (int j = i-step; j >=0 ; j-=step) {
if (arr[j]>arr[j+step]){
int temp = arr[j];
arr[j] = arr[j+step];
arr[j+step] = temp;
}
}
}
}
}
}