Selection Sort /*! * @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. */ 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); })(); Run Code