Java Reference
In-Depth Information
Scanner in = new Scanner(new FileReader("shell.in"));
int[] num = new int[MaxNumbers+1];
int n = 0, number;
while (in.hasNextInt()) {
number = in.nextInt();
if (n < MaxNumbers) num[++n] = number; //store if array has room
}
//perform Shell sort with increments 8, 3 and 1
hsort(num, n, 8);
hsort(num, n, 3);
hsort(num, n, 1);
for (int h = 1; h <= n; h++) {
System.out.printf("%d ", num[h]);
if (h % 10 == 0) System.out.printf("\n"); //print 10 numbers per line
}
System.out.printf("\n");
} //end main
public static void hsort(int[] A, int n, int h) {
for (int k = h + 1; k <= n; k++) {
int j = k - h;
int key = A[k];
while (j > 0 && key < A[j]) {
A[j + h] = A[j];
j = j - h;
}
A[j + h] = key;
} //end for
} //end hsort
} //end class ShellSortTest
Suppose shell.in contains the following numbers:
43 25 66 37 65 48 84 73 60 79 56 69 32 87 23 99 85 28 14 78 39 51 44 35
46 90 26 96 88 31 17 81 42 54 93 38 22 63 40 68 50 86 75 21 77 58 72 19
When Program P9.5 is run, it produces the following output:
14 17 19 21 22 23 25 26 28 31
32 35 37 38 39 40 42 43 44 46
48 50 51 54 56 58 60 63 65 66
68 69 72 73 75 77 78 79 81 84
85 86 87 88 90 93 96 99
Search WWH ::




Custom Search