希尔排序 先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。
1、选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;
2、按增量序列个数k,对序列进行k 趟排序;
3、每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1时,整个序列作为一个表来处理,表长度即为整个序列的长度。
public class ShellSort {
public static void Sort(int[] a) {
int j = 0;
int temp = 0;
// 每次将步长缩短为原来的一半
for (int increment = a.length / 2; increment > 0; increment /= 2) {// 多少轮
for (int i = increment; i < a.length; i++) {// 每一轮进行比较
temp = a[i];
for (j = i; j >= increment; j -= increment) {// 每一次进行比较
if (temp > a[j - increment]) {// 如果需要从小到大排列可以在此修改
a[j] = a[j - increment];
} else {
break;
}
}
a[j] = temp;
}
}
}
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27 };
Sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}