Selection Sort
Posted by Dustin Boston in Algorithms.
Selection sort is a comparison-based sorting algorithm that divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
- Time complexity is Quadratic, i.e. O(n^2)
- Space complexity is Constant, i.e. O(1)
Source Code Listing
code.ts
/*!
* @file Implements algorithm in TypeScript.
* @author Dustin Boston <mail@dustin.boston>
* @see Cormen, T, Leiserson, C, Rivest, R, and Stein, C. (2001).
* *Introduction to Algorithms*. (2nd ed). The MIT Press.
*/
/**
* Sorts an array of numbers using the selection sort algorithm.
*
* @param {number[]} array - The array of numbers to sort.
* @returns {void} The function sorts the array in place.
*/
export function selectionSort(array: number[]): void {
const length = array.length;
let currentIndex: number;
let minIndex: number;
let compareIndex: number;
let temporary: number;
for (currentIndex = 0; currentIndex < length; currentIndex += 1) {
minIndex = currentIndex;
for (
compareIndex = currentIndex + 1;
compareIndex < length;
compareIndex += 1
) {
if (array[compareIndex] < array[minIndex]) {
minIndex = compareIndex;
}
}
// Swapping the elements
temporary = array[currentIndex];
array[currentIndex] = array[minIndex];
array[minIndex] = temporary;
}
}
code_test.ts
import {expect, test} from "bun:test";
import {selectionSort} from "./code";
test("selectionSort", () => {
const a = [5, 2, 4, 6, 1, 3];
selectionSort(a);
expect(a.toString()).toBe("1,2,3,4,5,6");
const b = [31, 41, 59, 26, 41, 58];
selectionSort(b);
expect(b.toString()).toBe("26,31,41,41,58,59");
});