selection sort (#2177)

* selection sort

* Formatted with Google Java Formatter

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Du Yuanchao 2021-04-12 19:16:37 +08:00 committed by GitHub
parent d93ee0de2d
commit cebd052c94
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,68 +1,47 @@
package Sorts; package Sorts;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see SortAlgorithm
*/
public class SelectionSort implements SortAlgorithm { public class SelectionSort implements SortAlgorithm {
/** /**
* This method swaps the two elements in the array * Generic selection sort algorithm in increasing order.
* *
* @param <T> * @param arr the array to be sorted.
* @param arr, i, j The array for the swap and the indexes of the to-swap elements * @param <T> the class of array.
*/ * @return sorted array.
public <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* This method implements the Generic Selection Sort
*
* @param arr The array to be sorted Sorts the array in increasing order
*/ */
@Override @Override
public <T extends Comparable<T>> T[] sort(T[] arr) { public <T extends Comparable<T>> T[] sort(T[] arr) {
int n = arr.length; int n = arr.length;
for (int i = 0; i < n - 1; i++) { for (int i = 0; i < n - 1; i++) {
// Initial index of min int minIndex = i;
int min = i;
for (int j = i + 1; j < n; j++) { for (int j = i + 1; j < n; j++) {
if (arr[min].compareTo(arr[j]) > 0) { if (arr[minIndex].compareTo(arr[j]) > 0) {
min = j; minIndex = j;
} }
} }
if (minIndex != i) {
// Swapping if index of min is changed T temp = arr[i];
if (min != i) { arr[i] = arr[minIndex];
swap(arr, i, min); arr[minIndex] = temp;
} }
} }
return arr; return arr;
} }
// Driver Program /** Driver Code */
public static void main(String[] args) { public static void main(String[] args) {
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
SelectionSort selectionSort = new SelectionSort(); SelectionSort selectionSort = new SelectionSort();
Integer[] sorted = selectionSort.sort(arr); Integer[] sorted = selectionSort.sort(arr);
for (int i = 0; i < sorted.length - 1; ++i) {
assert sorted[i] <= sorted[i + 1];
}
// Output => 1 4 6 9 12 23 54 78 231
SortUtils.print(sorted);
// String Input
String[] strings = {"c", "a", "e", "b", "d"}; String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = selectionSort.sort(strings); String[] sortedStrings = selectionSort.sort(strings);
for (int i = 0; i < sortedStrings.length - 1; ++i) {
// Output => a b c d e assert strings[i].compareTo(strings[i + 1]) <= 0;
SortUtils.print(sortedStrings); }
} }
} }