Selection Sort
Posted by Dustin Boston .
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;
}
}
(() => {
const a = [5, 2, 4, 6, 1, 3];
selectionSort(a);
if (a.toString() !== "1,2,3,4,5,6") {
throw new Error("Did not sort correctly");
}
console.log("Sorted array:", a);
})();
selection_sort_test.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.
*/
import {selectionSort} from "../../../../data/algorithms/src/selection_sort.ts";
import {assert} from "$assert";
const a = [5, 2, 4, 6, 1, 3];
selectionSort(a);
assert(a.toString() === "1,2,3,4,5,6");
const b = [31, 41, 59, 26, 41, 58];
selectionSort(b);
assert(b.toString() === "26,31,41,41,58,59");