|
1 | 1 | packageSorts; |
2 | 2 |
|
3 | | -/** |
4 | | - * @author Varun Upadhyay (https://github.com/varunu28) |
5 | | - * @author Podshivalov Nikita (https://github.com/nikitap492) |
6 | | - * @see SortAlgorithm |
7 | | - */ |
8 | 3 | publicclassSelectionSortimplementsSortAlgorithm { |
9 | 4 |
|
10 | 5 | /** |
11 | | - *This method swaps the two elementsinthe array |
| 6 | + *Generic selection sort algorithminincreasing order. |
12 | 7 | * |
13 | | - * @param <T> |
14 | | - * @param arr, i, j The array for the swap and the indexes of the to-swap elements |
15 | | - */ |
16 | | -public <T>voidswap(T[]arr,inti,intj) { |
17 | | -Ttemp =arr[i]; |
18 | | -arr[i] =arr[j]; |
19 | | -arr[j] =temp; |
20 | | - } |
21 | | - |
22 | | -/** |
23 | | - * This method implements the Generic Selection Sort |
24 | | - * |
25 | | - * @param arr The array to be sorted Sorts the array in increasing order |
| 8 | + * @param arr the array to be sorted. |
| 9 | + * @param <T> the class of array. |
| 10 | + * @return sorted array. |
26 | 11 | */ |
27 | 12 | @Override |
28 | 13 | public <TextendsComparable<T>>T[]sort(T[]arr) { |
29 | 14 | intn =arr.length; |
30 | 15 | for (inti =0;i <n -1;i++) { |
31 | | -// Initial index of min |
32 | | -intmin =i; |
33 | | - |
| 16 | +intminIndex =i; |
34 | 17 | for (intj =i +1;j <n;j++) { |
35 | | -if (arr[min].compareTo(arr[j]) >0) { |
36 | | -min =j; |
| 18 | +if (arr[minIndex].compareTo(arr[j]) >0) { |
| 19 | +minIndex =j; |
37 | 20 | } |
38 | 21 | } |
39 | | - |
40 | | -// Swapping if index of min is changed |
41 | | -if (min !=i) { |
42 | | -swap(arr,i,min); |
| 22 | +if (minIndex !=i) { |
| 23 | +Ttemp =arr[i]; |
| 24 | +arr[i] =arr[minIndex]; |
| 25 | +arr[minIndex] =temp; |
43 | 26 | } |
44 | 27 | } |
45 | | - |
46 | 28 | returnarr; |
47 | 29 | } |
48 | 30 |
|
49 | | -// DriverProgram |
| 31 | +/** DriverCode */ |
50 | 32 | publicstaticvoidmain(String[]args) { |
51 | 33 |
|
52 | 34 | Integer[]arr = {4,23,6,78,1,54,231,9,12}; |
53 | | - |
54 | 35 | SelectionSortselectionSort =newSelectionSort(); |
55 | | - |
56 | 36 | Integer[]sorted =selectionSort.sort(arr); |
| 37 | +for (inti =0;i <sorted.length -1; ++i) { |
| 38 | +assertsorted[i] <=sorted[i +1]; |
| 39 | + } |
57 | 40 |
|
58 | | -// Output => 1 4 6912235478231 |
59 | | -SortUtils.print(sorted); |
60 | | - |
61 | | -// String Input |
62 | 41 | String[]strings = {"c","a","e","b","d"}; |
63 | 42 | String[]sortedStrings =selectionSort.sort(strings); |
64 | | - |
65 | | -// Output => ab c de |
66 | | -SortUtils.print(sortedStrings); |
| 43 | +for (inti =0;i <sortedStrings.length -1; ++i) { |
| 44 | +assertstrings[i].compareTo(strings[i +1]) <=0; |
| 45 | +} |
67 | 46 | } |
68 | 47 | } |