JavaAlgorithms/Sorts/SelectionSort.java

48 lines
1.2 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
2018-04-09 17:12:30 +08:00
public class SelectionSort implements SortAlgorithm {
2020-10-24 18:23:28 +08:00
/**
* Generic selection sort algorithm in increasing order.
2020-10-24 18:23:28 +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++) {
int minIndex = i;
2020-10-24 18:23:28 +08:00
for (int j = i + 1; j < n; j++) {
if (arr[minIndex].compareTo(arr[j]) > 0) {
minIndex = j;
}
2020-10-24 18:23:28 +08:00
}
if (minIndex != i) {
T temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
2020-10-24 18:23:28 +08:00
}
}
2020-10-24 18:23:28 +08:00
return arr;
}
/** Driver Code */
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
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);
for (int i = 0; i < sorted.length - 1; ++i) {
assert sorted[i] <= sorted[i + 1];
}
2020-10-24 18:23:28 +08:00
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = selectionSort.sort(strings);
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
}
}