Skip to content

selection sort #2177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 18 additions & 39 deletions Sorts/SelectionSort.java
Original file line number Diff line number Diff line change
@@ -1,68 +1,47 @@
package Sorts;

/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see 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, 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;
}

/**
* This method implements the Generic Selection Sort
*
* @param arr The array to be sorted Sorts the array in increasing order
* @param arr the array to be sorted.
* @param <T> the class of array.
* @return sorted array.
*/
@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;

int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[min].compareTo(arr[j]) > 0) {
min = j;
if (arr[minIndex].compareTo(arr[j]) > 0) {
minIndex = j;
}
}

// Swapping if index of min is changed
if (min != i) {
swap(arr, i, min);
if (minIndex != i) {
T temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

return arr;
}

// Driver Program
/** Driver Code */
public static void main(String[] args) {

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];
}

// Output => 1 4 6 9 12 23 54 78 231
SortUtils.print(sorted);

// String Input
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = selectionSort.sort(strings);

// Output => a b c d e
SortUtils.print(sortedStrings);
for (int i = 0; i < sortedStrings.length - 1; ++i) {
assert strings[i].compareTo(strings[i + 1]) <= 0;
}
}
}