希爾排序基本思想
設待排元素序列有n個元素,首先取一個整數d(d小於n)作爲間隔,將全部元素分爲d個子序列,所有距離爲d的元素放在一個子序列中,在每個子序列中分別進行直接插入排序,然後縮小間隔d重複上述過程,直到d=1將所有元素放在一個子序列中排序爲止。
即先對排序序列做“宏觀”調整,“跳躍式”插入排序,最後做微觀調整,一般此時已經基本有序,所以希爾排序又稱爲縮小增量排序
d,增量。d越大,子序列個數越多,子序列長度越小;d越小,子序列個數越少,子序列長度越大。
import java.util.Scanner;
import org.junit.Test;
public class Main3 {
/**
* 希爾排序
* @param a 待排序數組
* @return 排好序數組
*/
public static int[] shellSort(int[] a) {
int left = 0;// 數組左邊界下標
int right = a.length - 1;// 數組右邊界下標
int gap=right-left-1;//增量的初始值
do{
gap=gap/3+1;//下一個增量值
for (int i =left+gap; i <=right; i++) {//各子序列交替處理
if(a[i]<a[i-gap]){//向前搜索,每次跳躍gap
int temp=a[i];
int j=i-gap;
do{
a[j+gap]=a[j];//後移元素
j-=gap;
}while(j>=left && temp<a[j]);//再比較前一個元素
a[j+gap]=temp; //插入
}
}
}while(gap>1);
return a;
}
@Test
public void testShellSort() {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入數組長度!");
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("請輸入數組元素");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int[] result = shellSort(a);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
}
}
}