I tried to implement the shell-sort algorithm using this Java code:
// Using Pratt sequence
public static void hSort(int tab[]) {
int N = tab.length;
int k = 0;
int sequence = 1;
// Getting the final term of the pratt sequence
while(((int)(Math.pow(3, k) - 1) / 2) < N/3) {
sequence = (int)(Math.pow(3, k) - 1) / 2;
k++;
}
k--;
while(sequence > 0) {
hInsertionSort(tab, sequence);
k--;
sequence = (int)(Math.pow(3, k) - 1) / 2;
}
}
// H sorting using insertion sort
public static void hInsertionSort(int[] tab, int h) {
int N = tab.length;
int k = 0;
while (k < h) {
for (int i = k; i < N; i+=h) {
for (int j = i; j > k+h-1; j-=h) {
if (less(tab[j], tab[j-h]) == -1) exch(tab, j, j-h);
else break;
}
}
k++;
}
}
You can use the hsort method to try sort a table of integers.
Is the complexity of this implementation the same as the usual implementation?
hlooks an ill-chosen name.)(doc-comment your java-code.) InhInsertionSort(int[] tab, int h), you use awhile-loop around twofor-loops; from outer to inner loop, the iteration variables readk,i,j: why? In the inner loop, I'd writeif (less(tab[j], tab[j-h]) != -1) break, followed by an "unconditional" exchange. \$\endgroup\$