代码实现如下:
package g;
public class ShellSort {
public static int[] randomInt(int n, int size) {
int[] x = new int[n];
for (int i = 0; i < x.length; i++) {
x[i] = (int) (Math.random() * size);
}
return x;
}
public static void print(int[] value) {
/*利用for each来输出,格式为:for(类型 变量 :数组)
* 其中,<类型>是<数组>的元素类型,<类型>的<变量>获得<数组>的每一个元素。
*/
for (int i : value) {
System.out.print(i + " ");
}
}
public static void shellSort(int[] keys) {
for (int delta = keys.length / 2; delta > 0; delta /= 2) {
for (int i = delta; i < keys.length; i++) {
int temp = keys[i];
int j;
for (j = i - delta; j >= 0 && temp < keys[j]; j -= delta) {
keys[j + delta] = keys[j];
}
keys[j + delta] = temp;
}
System.out.println("\ndelta=" + delta);
print(keys);
}
}
public static void main(String[] args) {
int[] values = ShellSort.randomInt(9, 100);
System.out.print("关键字序列:");
ShellSort.print(values);
ShellSort.shellSort(values);
}
}
输出如下:
关键字序列:92 76 12 44 85 37 68 81 94
delta=4
85 37 12 44 92 76 68 81 94
delta=2
12 37 68 44 85 76 92 81 94
delta=1
12 37 44 68 76 81 85 92 94