|
1 | 1 | package Sorts; |
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 | public class SelectionSort implements SortAlgorithm { |
9 | 4 |
|
10 | 5 | /** |
11 | | - * This method swaps the two elements in the array |
| 6 | + * Generic selection sort algorithm in increasing 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> void swap(T[] arr, int i, int j) { |
17 | | - T temp = 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 <T extends Comparable<T>> T[] sort(T[] arr) { |
29 | 14 | int n = arr.length; |
30 | 15 | for (int i = 0; i < n - 1; i++) { |
31 | | - // Initial index of min |
32 | | - int min = i; |
33 | | - |
| 16 | + int minIndex = i; |
34 | 17 | for (int j = 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 | + T temp = arr[i]; |
| 24 | + arr[i] = arr[minIndex]; |
| 25 | + arr[minIndex] = temp; |
43 | 26 | } |
44 | 27 | } |
45 | | - |
46 | 28 | return arr; |
47 | 29 | } |
48 | 30 |
|
49 | | - // Driver Program |
| 31 | + /** Driver Code */ |
50 | 32 | public static void main(String[] args) { |
51 | 33 |
|
52 | 34 | Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; |
53 | | - |
54 | 35 | SelectionSort selectionSort = new SelectionSort(); |
55 | | - |
56 | 36 | Integer[] sorted = selectionSort.sort(arr); |
| 37 | + for (int i = 0; i < sorted.length - 1; ++i) { |
| 38 | + assert sorted[i] <= sorted[i + 1]; |
| 39 | + } |
57 | 40 |
|
58 | | - // Output => 1 4 6 9 12 23 54 78 231 |
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 => a b c d e |
66 | | - SortUtils.print(sortedStrings); |
| 43 | + for (int i = 0; i < sortedStrings.length - 1; ++i) { |
| 44 | + assert strings[i].compareTo(strings[i + 1]) <= 0; |
| 45 | + } |
67 | 46 | } |
68 | 47 | } |
0 commit comments