希尔排序
需求:
排序前:{9,1,2,5,7,4,8,6,3,5}
排序后:{1,2,3,4,5,5,6,7,8,9}
算法设计
Shell类:
package suanfa;
public class Shell {
public static void sort(Comparable[] a){
// 先确定增长量
int h = 1;
while(h < a.length / 2) {
h = 2 * h + 1;
}
// 按照 h 值进行排序
while(h >= 1){
for(int i = h; i < a.length; i++) {
for(int j = i; j >= h; j -= h) {
if(greater(a[j - h], a[j])) {
exch(a, j - h, j);
} else {
break;
}
}
}
h = h / 2;
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
ShellTest类:
package suanfa;
import java.util.Arrays;
public class ShellTest {
public static void main(String[] args) {
Integer[] a={9,1,2,5,7,4,8,6,3,5};
Shell.sort(a);
System.out.println(Arrays.toString(a));
}
}
录制: untitled2 – Shell.java
录制文件:https://meeting.tencent.com/crm/ldR1Qz8Pfb