|
1 | 1 | package com.thealgorithms.sorts;
|
2 | 2 |
|
3 | 3 | public class SelectionSort implements SortAlgorithm {
|
4 |
| - |
5 | 4 | /**
|
6 |
| - * Generic selection sort algorithm in increasing order. |
| 5 | + * Sorts an array of comparable elements in increasing order using the selection sort algorithm. |
7 | 6 | *
|
8 |
| - * @param arr the array to be sorted. |
9 |
| - * @param <T> the class of array. |
10 |
| - * @return sorted array. |
| 7 | + * @param array the array to be sorted |
| 8 | + * @param <T> the class of array elements |
| 9 | + * @return the sorted array |
11 | 10 | */
|
12 | 11 | @Override
|
13 |
| - public <T extends Comparable<T>> T[] sort(T[] arr) { |
14 |
| - int n = arr.length; |
15 |
| - for (int i = 0; i < n - 1; i++) { |
16 |
| - int minIndex = i; |
17 |
| - for (int j = i + 1; j < n; j++) { |
18 |
| - if (arr[minIndex].compareTo(arr[j]) > 0) { |
19 |
| - minIndex = j; |
20 |
| - } |
21 |
| - } |
22 |
| - if (minIndex != i) { |
23 |
| - SortUtils.swap(arr, i, minIndex); |
24 |
| - } |
25 |
| - } |
26 |
| - return arr; |
27 |
| - } |
| 12 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
| 13 | + // One by one move the boundary of the unsorted subarray |
| 14 | + for (int i = 0; i < array.length - 1; i++) { |
28 | 15 |
|
29 |
| - /** |
30 |
| - * Driver Code |
31 |
| - */ |
32 |
| - public static void main(String[] args) { |
33 |
| - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; |
34 |
| - SelectionSort selectionSort = new SelectionSort(); |
35 |
| - Integer[] sorted = selectionSort.sort(arr); |
36 |
| - for (int i = 0; i < sorted.length - 1; ++i) { |
37 |
| - assert sorted[i] <= sorted[i + 1]; |
| 16 | + // Swap the remaining minimum element with the current element |
| 17 | + SortUtils.swap(array, i, findIndexOfMin(array, i)); |
38 | 18 | }
|
| 19 | + return array; |
| 20 | + } |
39 | 21 |
|
40 |
| - String[] strings = {"c", "a", "e", "b", "d"}; |
41 |
| - String[] sortedStrings = selectionSort.sort(strings); |
42 |
| - for (int i = 0; i < sortedStrings.length - 1; ++i) { |
43 |
| - assert strings[i].compareTo(strings[i + 1]) <= 0; |
| 22 | + private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int start) { |
| 23 | + int minIndex = start; |
| 24 | + for (int i = start + 1; i < array.length; i++) { |
| 25 | + if (array[i].compareTo(array[minIndex]) < 0) { |
| 26 | + minIndex = i; |
| 27 | + } |
44 | 28 | }
|
| 29 | + return minIndex; |
45 | 30 | }
|
46 | 31 | }
|
0 commit comments