|
| 1 | +packageSorts; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author dpunosevac |
| 5 | + */ |
| 6 | +publicclassShellSort { |
| 7 | + |
| 8 | +/** |
| 9 | + * This method implements Generic Shell Sort. |
| 10 | + * @param array The array to be sorted |
| 11 | + */ |
| 12 | +publicstaticvoidshellSort(Comparable[]array) { |
| 13 | +intN =array.length; |
| 14 | +inth =1; |
| 15 | + |
| 16 | +while (h <N/3) { |
| 17 | +h =3 *h +1; |
| 18 | + } |
| 19 | + |
| 20 | +while (h >=1) { |
| 21 | +for (inti =h;i <N;i++) { |
| 22 | +for (intj =i;j >=h &&less(array[j],array[j-h]);j -=h) { |
| 23 | +exch(array,j,j -h); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | +h /=3; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | +/** |
| 32 | + * Helper method for exchanging places in array |
| 33 | + * @param array The array which elements we want to swap |
| 34 | + * @param i index of the first element |
| 35 | + * @param j index of the second element |
| 36 | + */ |
| 37 | +privatestaticvoidexch(Comparable[]array,inti,intj) { |
| 38 | +Comparableswap =array[i]; |
| 39 | +array[i] =array[j]; |
| 40 | +array[j] =swap; |
| 41 | + } |
| 42 | + |
| 43 | +/** |
| 44 | + * This method checks if first element is less then the other element |
| 45 | + * @param v first element |
| 46 | + * @param w second element |
| 47 | + * @return true if the first element is less then the second element |
| 48 | + */ |
| 49 | +privatestaticbooleanless(Comparablev,Comparablew) { |
| 50 | +returnv.compareTo(w) <0; |
| 51 | + } |
| 52 | + |
| 53 | +publicstaticvoidmain(String[]args) { |
| 54 | +// Integer Input |
| 55 | +int[]arr1 = {4,23,6,78,1,54,231,9,12}; |
| 56 | +Integer[]array =newInteger[arr1.length]; |
| 57 | + |
| 58 | +for (inti=0;i<arr1.length;i++) { |
| 59 | +array[i] =arr1[i]; |
| 60 | + } |
| 61 | + |
| 62 | +shellSort(array); |
| 63 | + |
| 64 | +for (inti =0;i <array.length;i++) { |
| 65 | +System.out.println(array[i]); |
| 66 | + } |
| 67 | + } |
| 68 | +} |