1
1
package com .thealgorithms .sorts ;
2
2
3
+ /**
4
+ * This class provides an implementation of the selection sort algorithm.
5
+ * It sorts an array of elements in increasing order using an iterative approach.
6
+ */
3
7
public class SelectionSort implements SortAlgorithm {
4
8
5
9
/**
6
- * Generic selection sort algorithm in increasing order.
10
+ * Sorts an array of comparable elements in increasing order using the selection sort algorithm .
7
11
*
8
- * @param arr the array to be sorted.
9
- * @param <T> the class of array.
10
- * @return sorted array.
12
+ * @param array the array to be sorted
13
+ * @param <T> the class of array elements
14
+ * @return the sorted array
11
15
*/
12
16
@ 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 ++) {
17
+ public <T extends Comparable <T >> T [] sort (T [] array ) {
18
+ if (array .length == 0 ) {
19
+ return array ;
20
+ }
21
+
22
+ // One by one move the boundary of the unsorted subarray
23
+ for (int i = 0 ; i < array .length - 1 ; i ++) {
24
+ // Find the minimum element in the unsorted array
16
25
int minIndex = i ;
17
- for (int j = i + 1 ; j < n ; j ++) {
18
- if (arr [ minIndex ].compareTo (arr [ j ]) > 0 ) {
26
+ for (int j = i + 1 ; j < array . length ; j ++) {
27
+ if (array [ j ].compareTo (array [ minIndex ]) < 0 ) {
19
28
minIndex = j ;
20
29
}
21
30
}
31
+
32
+ // Swap the found minimum element with the first element
22
33
if (minIndex != i ) {
23
- SortUtils .swap (arr , i , minIndex );
34
+ SortUtils .swap (array , i , minIndex );
24
35
}
25
36
}
26
- return arr ;
27
- }
28
-
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 ];
38
- }
39
-
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 ;
44
- }
37
+ return array ;
45
38
}
46
- }
39
+ }
0 commit comments