|
1 | 1 | package Sorts;
|
2 | 2 |
|
| 3 | +import static Sorts.SortUtils.*; |
| 4 | + |
| 5 | + |
3 | 6 | /**
|
4 | 7 | * @author dpunosevac
|
| 8 | + * @author Podshivalov Nikita (https://github.com/nikitap492) |
| 9 | + * |
| 10 | + * @see SortAlgorithm |
| 11 | + * |
5 | 12 | */
|
6 |
| -public class ShellSort { |
| 13 | +public class ShellSort implements SortAlgorithm { |
7 | 14 |
|
8 | 15 | /**
|
9 | 16 | * This method implements Generic Shell Sort.
|
10 | 17 | * @param array The array to be sorted
|
11 | 18 | */
|
12 |
| - public static void shellSort(Comparable[] array) { |
| 19 | + @Override |
| 20 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
13 | 21 | int N = array.length;
|
14 | 22 | int h = 1;
|
15 | 23 |
|
16 | 24 | while (h < N/3) {
|
17 |
| - h = 3 * h + 1; |
| 25 | + h = 3 * h + 1; |
18 | 26 | }
|
19 | 27 |
|
20 | 28 | while (h >= 1) {
|
21 |
| - for (int i = h; i < N; i++) { |
22 |
| - for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) { |
23 |
| - exch(array, j, j - h); |
| 29 | + for (int i = h; i < N; i++) { |
| 30 | + for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) { |
| 31 | + swap(array, j, j - h); |
| 32 | + } |
24 | 33 | }
|
25 |
| - } |
26 | 34 |
|
27 |
| - h /= 3; |
| 35 | + h /= 3; |
28 | 36 | }
|
29 |
| - } |
30 | 37 |
|
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 |
| - private static void exch(Comparable[] array, int i, int j) { |
38 |
| - Comparable swap = 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 |
| - private static boolean less(Comparable v, Comparable w) { |
50 |
| - return v.compareTo(w) < 0; |
| 38 | + return array; |
51 | 39 | }
|
52 | 40 |
|
53 | 41 | public static void main(String[] args) {
|
54 |
| - // Integer Input |
55 |
| - int[] arr1 = {4,23,6,78,1,54,231,9,12}; |
56 |
| - Integer[] array = new Integer[arr1.length]; |
| 42 | + Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; |
57 | 43 |
|
58 |
| - for (int i=0;i<arr1.length;i++) { |
59 |
| - array[i] = arr1[i]; |
60 |
| - } |
| 44 | + ShellSort sort = new ShellSort(); |
| 45 | + Integer[] sorted = sort.sort(toSort); |
61 | 46 |
|
62 |
| - shellSort(array); |
| 47 | + print(sorted); |
63 | 48 |
|
64 |
| - for (int i = 0; i < array.length; i++) { |
65 |
| - System.out.println(array[i]); |
66 |
| - } |
67 | 49 | }
|
68 | 50 | }
|
0 commit comments