2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-09 17:12:30 +08:00
|
|
|
|
|
|
|
public class SelectionSort implements SortAlgorithm {
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
2021-04-12 19:16:37 +08:00
|
|
|
* Generic selection sort algorithm in increasing order.
|
2020-10-24 18:23:28 +08:00
|
|
|
*
|
2021-04-12 19:16:37 +08:00
|
|
|
* @param arr the array to be sorted.
|
|
|
|
* @param <T> the class of array.
|
|
|
|
* @return sorted array.
|
2020-10-24 18:23:28 +08:00
|
|
|
*/
|
|
|
|
@Override
|
|
|
|
public <T extends Comparable<T>> T[] sort(T[] arr) {
|
|
|
|
int n = arr.length;
|
|
|
|
for (int i = 0; i < n - 1; i++) {
|
2021-04-12 19:16:37 +08:00
|
|
|
int minIndex = i;
|
2020-10-24 18:23:28 +08:00
|
|
|
for (int j = i + 1; j < n; j++) {
|
2021-04-12 19:16:37 +08:00
|
|
|
if (arr[minIndex].compareTo(arr[j]) > 0) {
|
|
|
|
minIndex = j;
|
2017-09-08 10:11:35 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
2021-04-12 19:16:37 +08:00
|
|
|
if (minIndex != i) {
|
|
|
|
T temp = arr[i];
|
|
|
|
arr[i] = arr[minIndex];
|
|
|
|
arr[minIndex] = temp;
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
2017-09-08 10:11:35 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
return arr;
|
|
|
|
}
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2021-04-12 19:16:37 +08:00
|
|
|
/** Driver Code */
|
2020-10-24 18:23:28 +08:00
|
|
|
public static void main(String[] args) {
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
|
|
|
|
SelectionSort selectionSort = new SelectionSort();
|
|
|
|
Integer[] sorted = selectionSort.sort(arr);
|
2021-04-12 19:16:37 +08:00
|
|
|
for (int i = 0; i < sorted.length - 1; ++i) {
|
|
|
|
assert sorted[i] <= sorted[i + 1];
|
|
|
|
}
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
String[] strings = {"c", "a", "e", "b", "d"};
|
|
|
|
String[] sortedStrings = selectionSort.sort(strings);
|
2021-04-12 19:16:37 +08:00
|
|
|
for (int i = 0; i < sortedStrings.length - 1; ++i) {
|
|
|
|
assert strings[i].compareTo(strings[i + 1]) <= 0;
|
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
2017-04-27 22:29:41 +08:00
|
|
|
}
|