|
| 1 | +// Java implementation of ShellSort |
| 2 | +class ShellSort |
| 3 | +{ |
| 4 | + /* An utility function to print array of size n*/ |
| 5 | + static void printArray(int arr[]) |
| 6 | + { |
| 7 | + int n = arr.length; |
| 8 | + for (int i=0; i<n; ++i) |
| 9 | + System.out.print(arr[i] + " "); |
| 10 | + System.out.println(); |
| 11 | + } |
| 12 | + |
| 13 | + /* function to sort arr using shellSort */ |
| 14 | + int sort(int arr[]) |
| 15 | + { |
| 16 | + int n = arr.length; |
| 17 | + |
| 18 | + // Start with a big gap, then reduce the gap |
| 19 | + for (int gap = n/2; gap > 0; gap /= 2) |
| 20 | + { |
| 21 | + // Do a gapped insertion sort for this gap size. |
| 22 | + // The first gap elements a[0..gap-1] are already |
| 23 | + // in gapped order keep adding one more element |
| 24 | + // until the entire array is gap sorted |
| 25 | + for (int i = gap; i < n; i += 1) |
| 26 | + { |
| 27 | + // add a[i] to the elements that have been gap |
| 28 | + // sorted save a[i] in temp and make a hole at |
| 29 | + // position i |
| 30 | + int temp = arr[i]; |
| 31 | + |
| 32 | + // shift earlier gap-sorted elements up until |
| 33 | + // the correct location for a[i] is found |
| 34 | + int j; |
| 35 | + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) |
| 36 | + arr[j] = arr[j - gap]; |
| 37 | + |
| 38 | + // put temp (the original a[i]) in its correct |
| 39 | + // location |
| 40 | + arr[j] = temp; |
| 41 | + } |
| 42 | + } |
| 43 | + return 0; |
| 44 | + } |
| 45 | + |
| 46 | + // Driver method |
| 47 | + public static void main(String args[]) |
| 48 | + { |
| 49 | + int arr[] = {12, 34, 54, 2, 3}; |
| 50 | + System.out.println("Array before sorting"); |
| 51 | + printArray(arr); |
| 52 | + |
| 53 | + ShellSort ob = new ShellSort(); |
| 54 | + ob.sort(arr); |
| 55 | + |
| 56 | + System.out.println("Array after sorting"); |
| 57 | + printArray(arr); |
| 58 | + } |
| 59 | +} |
0 commit comments