如果h很大,则元素移动很远。 (1)、 h 从1开始 (2)、 h < N / 3 (3)、 h = 3 * h + 1 h = 4
L
E
E
A
M
H
L
E
P
S
O
L
T
S
X
R
L
-
-
-
M
-
-
-
P
-
-
-
T
E
-
-
-
H
-
-
-
S
-
-
-
S
E
-
-
-
L
-
-
-
O
-
-
-
X
A
-
-
-
E
-
-
-
L
-
-
-
R
实现
publicclassShell{publicstaticvoidsort(Comparable[] a){intN= a.length;int h =1;while(h <N/3){
h =3* h +1;}while(h >=1){for(int i = h; i <N; i++){for(int j = i; j >= h &&less(a[j], a[j-h]); j-= h){exch(a, j, j-h);}}
h = h /3;}}privatestaticbooleanless(Comparable v,Comparable w){return v.compareTo(w)<0;}privatestaticvoidexch(Comparable[] a,int i,int j){Comparable t = a[i];
a[i]= a[j];
a[j]= t;}privatestaticbooleanisSorted(Comparable[] a){for(int i =1; i < a.length; i++){if(less(a[i], a[i -1])){returnfalse;}}returntrue;}privatestaticvoidshow(Comparable[] a){for(int i =0; i < a.length; i++)System.out.print(a[i]+" ");System.out.println();}publicstaticvoidmain(String[] args){String[] a ={"S","H","E","L","L","S","O","R","T","E","X","A","M","P","L","E"};Stopwatch time =newStopwatch();sort(a);double timer = time.elapsedTime();if(isSorted(a)){show(a);System.out.println("time: "+ timer);}else{System.out.println("false");}}}