2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-09 17:12:30 +08:00
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
/**
|
2017-09-08 10:11:35 +08:00
|
|
|
* @author Varun Upadhyay (https://github.com/varunu28)
|
2018-04-09 18:25:02 +08:00
|
|
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
|
|
|
* @see SortAlgorithm
|
2017-04-18 22:57:17 +08:00
|
|
|
*/
|
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
|
|
|
/**
|
|
|
|
* This method swaps the two elements in the array
|
|
|
|
*
|
|
|
|
* @param <T>
|
|
|
|
* @param arr, i, j The array for the swap and the indexes of the to-swap elements
|
|
|
|
*/
|
|
|
|
public <T> void swap(T[] arr, int i, int j) {
|
|
|
|
T temp = arr[i];
|
|
|
|
arr[i] = arr[j];
|
|
|
|
arr[j] = temp;
|
|
|
|
}
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* This method implements the Generic Selection Sort
|
|
|
|
*
|
|
|
|
* @param arr The array to be sorted Sorts the array in increasing order
|
|
|
|
*/
|
|
|
|
@Override
|
|
|
|
public <T extends Comparable<T>> T[] sort(T[] arr) {
|
|
|
|
int n = arr.length;
|
|
|
|
for (int i = 0; i < n - 1; i++) {
|
|
|
|
// Initial index of min
|
|
|
|
int min = i;
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
for (int j = i + 1; j < n; j++) {
|
2021-03-14 09:38:57 +08:00
|
|
|
if (arr[min].compareTo(arr[j]) > 0) {
|
2020-10-24 18:23:28 +08:00
|
|
|
min = j;
|
2017-09-08 10:11:35 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
2018-04-09 17:12:30 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// Swapping if index of min is changed
|
|
|
|
if (min != i) {
|
|
|
|
swap(arr, i, min);
|
|
|
|
}
|
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
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// Driver Program
|
|
|
|
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};
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
SelectionSort selectionSort = new SelectionSort();
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
Integer[] sorted = selectionSort.sort(arr);
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// Output => 1 4 6 9 12 23 54 78 231
|
|
|
|
SortUtils.print(sorted);
|
2017-09-08 10:11:35 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// String Input
|
|
|
|
String[] strings = {"c", "a", "e", "b", "d"};
|
|
|
|
String[] sortedStrings = selectionSort.sort(strings);
|
|
|
|
|
|
|
|
// Output => a b c d e
|
|
|
|
SortUtils.print(sortedStrings);
|
|
|
|
}
|
2017-04-27 22:29:41 +08:00
|
|
|
}
|