Shell sort java program
Shellsort: which increment sequence to use?
Powers of two. 1, 2, 4, 8, 16, 32, ... No.
Powers of two minus one. 1, 3, 7, 15, 31, 63, … Maybe.
3x + 1. 1, 4, 13, 40, 121, 364, … OK. Easy to compute.
class ShellSort {
public static void sort(int[] array) {
int N = array.length;
int h = 1;
while(h < N/3) {
// 3h +1 sequence
h = 3*h+1; // 1, 4, 13, 40, 121, 364, ...
}
while(h >=1) { // h-sort the array.
// insertion sort
for(int i = h; i < N; i++) {
for(int j = i; j >= h && less(array[j], array[j-h]); j -= h) {
swap(array, j, j-h);
}
}
h = h/3; // move to next increment
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static boolean less(int key1, int key2) {
return key1 < key2;
}
private static void display(int[] array) {
for(int key : array) {
System.out.print(key + " ");
}
}
public static void main (String[] args) {
int[] array = new int[] {11,13,7,12,16,9,24,5,10,3};
System.out.println("Unsorted array : ");
display(array);
sort(array);
System.out.println("\nSorted array : ");
display(array);
}
}
Unsorted array :
11 13 7 12 16 9 24 5 10 3
Sorted array :
3 5 7 9 10 11 12 13 16 24
Comments
Post a Comment