|
3 | 3 | importstaticSorts.SortUtils.less; |
4 | 4 | importstaticSorts.SortUtils.print; |
5 | 5 |
|
6 | | -/** |
7 | | - * @author Varun Upadhyay (https://github.com/varunu28) |
8 | | - * @author Podshivalov Nikita (https://github.com/nikitap492) |
9 | | - */ |
10 | 6 | classInsertionSortimplementsSortAlgorithm { |
11 | 7 |
|
12 | 8 | /** |
13 | | - *This method implements theGenericInsertion Sort Sorts the arrayin increasing order |
| 9 | + * Genericinsertion sort algorithmin 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 <TextendsComparable<T>>T[]sort(T[]array) { |
19 | | -for (intj =1;j <array.length;j++) { |
20 | | - |
21 | | -// Picking up the key(Card) |
22 | | -Tkey =array[j]; |
23 | | -inti =j -1; |
24 | | - |
25 | | -while (i >=0 &&less(key,array[i])) { |
26 | | -array[i +1] =array[i]; |
27 | | -i--; |
| 17 | +for (inti =1;i <array.length;i++) { |
| 18 | +TinsertValue =array[i]; |
| 19 | +intj; |
| 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 | returnarray; |
33 | 28 | } |
34 | 29 |
|
35 | | -// DriverProgram |
| 30 | +/** DriverCode */ |
36 | 31 | publicstaticvoidmain(String[]args) { |
37 | | -// Integer Input |
38 | 32 | Integer[]integers = {4,23,6,78,1,54,231,9,12}; |
39 | | - |
40 | 33 | InsertionSortsort =newInsertionSort(); |
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 => abcde |
53 | | -print(strings); |
| 39 | +print(strings);/* [a, b, c, d, e] */ |
54 | 40 | } |
55 | 41 | } |