Skip to content
Open
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
18 changes: 16 additions & 2 deletions src/main/java/com/thealgorithms/sorts/SelectionSort.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.thealgorithms.sorts;

/**
* Implementation of the Selection Sort algorithm.
*
* @see SortAlgorithm
*/
public class SelectionSort implements SortAlgorithm {
/**
* Generic Selection Sort algorithm.
Expand All @@ -11,18 +16,27 @@ public class SelectionSort implements SortAlgorithm {
*
* Space Complexity: O(1) – in-place sorting.
*
* @see SortAlgorithm
* @param array the array to be sorted
* @param <T> the type of elements in the array
* @return the sorted array
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {

for (int i = 0; i < array.length - 1; i++) {
final int minIndex = findIndexOfMin(array, i);
SortUtils.swap(array, i, minIndex);
}
return array;
}

/**
* Finds the index of the minimum element in the array starting from a given index.
*
* @param array the array to search
* @param startIndex the index to start searching from
* @param <T> the type of elements in the array
* @return the index of the minimum element
*/
private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int startIndex) {
int minIndex = startIndex;
for (int i = startIndex + 1; i < array.length; i++) {
Expand Down