Selection Sort Algorithm

Selection Sort algorithm is a simple comparison-based sorting technique that works by dividing the input list into two parts: sorted and unsorted. Initially, the sorted part is empty, and the unsorted part contains all the elements. The algorithm repeatedly selects the smallest (or largest, depending on the ordering) element from the unsorted part and moves it to the end of the sorted part. This process continues until the unsorted part becomes empty, and the sorted part contains all the elements in the desired order. In each iteration of the selection sort algorithm, the minimum (or maximum) element is identified from the remaining unsorted elements, and its position is swapped with the first unsorted element. This results in the minimum (or maximum) element moving to its correct position in the sorted part. The algorithm's time complexity is O(n^2) as it requires two nested loops in its implementation, making it inefficient for large datasets. However, it has the advantage of performing fewer swaps compared to other sorting algorithms like bubble sort, which might be beneficial in situations where swapping elements is a costly operation.
package sort

/**
 * This method implements the Generic Selection Sort
 *
 * @param array The array to be sorted
 * Sorts the array by repeatedly finding the minimum element from unsorted part and putting in the beginning
 *
 * Worst-case performance	O(n^2)
 * Best-case performance	O(n^2)
 * Average performance	O(n^2)
 * Worst-case space complexity	O(1)
 **/
fun <T: Comparable<T>> selectionSort(array: Array<T>) {
    val length = array.size - 1

    for (i in 0..length) {
        var idx = i
        for (j in i+1..length) {
            if (array[j] < array[idx]) {
                idx = j
            }
        }

        swapElements(array, i, idx)
    }
}

LANGUAGE:

DARK MODE: