|
3 | 3 | import static Sorts.SortUtils.less; |
4 | 4 | import static Sorts.SortUtils.print; |
5 | 5 |
|
6 | | -/** |
7 | | - * @author Varun Upadhyay (https://github.com/varunu28) |
8 | | - * @author Podshivalov Nikita (https://github.com/nikitap492) |
9 | | - */ |
10 | 6 | class InsertionSort implements SortAlgorithm { |
11 | 7 |
|
12 | 8 | /** |
13 | | - * This method implements the Generic Insertion Sort Sorts the array in increasing order |
| 9 | + * Generic insertion sort algorithm in increasing order. |
14 | 10 | * |
15 | | - * @param array The array to be sorted |
| 11 | + * @param array the array to be sorted. |
| 12 | + * @param <T> the class of array. |
| 13 | + * @return sorted array. |
16 | 14 | */ |
17 | 15 | @Override |
18 | 16 | public <T extends Comparable<T>> T[] sort(T[] array) { |
19 | | - for (int j = 1; j < array.length; j++) { |
20 | | - |
21 | | - // Picking up the key(Card) |
22 | | - T key = array[j]; |
23 | | - int i = j - 1; |
24 | | - |
25 | | - while (i >= 0 && less(key, array[i])) { |
26 | | - array[i + 1] = array[i]; |
27 | | - i--; |
| 17 | + for (int i = 1; i < array.length; i++) { |
| 18 | + T insertValue = array[i]; |
| 19 | + int j; |
| 20 | + for (j = i - 1; j >= 0 && less(insertValue, array[j]); j--) { |
| 21 | + array[j + 1] = array[j]; |
| 22 | + } |
| 23 | + if (j != i - 1) { |
| 24 | + array[j + 1] = insertValue; |
28 | 25 | } |
29 | | - // Placing the key (Card) at its correct position in the sorted subarray |
30 | | - array[i + 1] = key; |
31 | 26 | } |
32 | 27 | return array; |
33 | 28 | } |
34 | 29 |
|
35 | | - // Driver Program |
| 30 | + /** Driver Code */ |
36 | 31 | public static void main(String[] args) { |
37 | | - // Integer Input |
38 | 32 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; |
39 | | - |
40 | 33 | InsertionSort sort = new InsertionSort(); |
41 | | - |
42 | 34 | sort.sort(integers); |
| 35 | + print(integers); /* [1, 4, 6, 9, 12, 23, 54, 78, 231] */ |
43 | 36 |
|
44 | | - // Output => 1 4 6 9 12 23 54 78 231 |
45 | | - print(integers); |
46 | | - |
47 | | - // String Input |
48 | 37 | String[] strings = {"c", "a", "e", "b", "d"}; |
49 | | - |
50 | 38 | sort.sort(strings); |
51 | | - |
52 | | - // Output => a b c d e |
53 | | - print(strings); |
| 39 | + print(strings); /* [a, b, c, d, e] */ |
54 | 40 | } |
55 | 41 | } |
0 commit comments