- 希尔排序:直接插入排序的改良版,威力更强。
- 直接插入排序是每一移一个,比较相邻的两个
- 希尔排序第一次分堆是 n = n / 2为一堆的,也就是下标为i的元素和下标为i + n/2,i + n/2 +… < n的元素作为一堆的,
- 每次比较i 和 i + n /2 的元素,保证n[i] < n[i + n/2]
- 第二次分堆 step = n / 4,每次加step词,保证 i + step + …的次序
java代码:
package com.zhangyike.shellSort;
import java.util.Arrays;
import java.util.Random;
public class ShellSort {
public static void main(String args[]) {
int count = 10;
int n[] = new int[count];
Random rd = new Random();
for (int i = 0; i < n.length; i++) {
n[i] = rd.nextInt(count);
}
System.out.println("排序前:" + Arrays.toString(n));
shellSort(n,n.length);
System.out.println("排序后:" + Arrays.toString(n));
}
public static void shellSort(int[] n, int len){
int step = 0;
//选择步长
for (step = len/2; step > 0; step /= 2) {
//对改步长内的分组进行排序
for (int i = step; i < len; i++) {
int tmp = n[i];
int position = i;
//对改步长内的元素进行插入
while(position >= step && tmp < n[position - step]){
n[position] = n[position - step];
position -= step;
}
n[position] = tmp;
}
}
}
}