Bubblesort /*! * @file Bubblesort * @author Dustin Boston * @see Cormen, T, Leiserson, C, Rivest, R, and Stein, C. (2001). * Introduction to Algorithms. (2nd ed). The MIT Press. */ /** * Sorts an array using the bubble sort algorithm. * @param array The array to be sorted. */ function bubbleSort(array: number[]): void { for (let sortedIndex = 0; sortedIndex < array.length; sortedIndex++) { for (let currentIndex = array.length - 1; currentIndex > sortedIndex; currentIndex--) { if (array[currentIndex] < array[currentIndex - 1]) { const swap = array[currentIndex]; array[currentIndex] = array[currentIndex - 1]; array[currentIndex - 1] = swap; } } } } (() => { const a = [5, 2, 4, 6, 1, 3]; bubbleSort(a); if (a.toString() !== '1,2,3,4,5,6') { throw new Error(`Bubblesort failed: ${a.toString()}`); } })(); Run Code