Last active
March 25, 2024 03:39
-
-
Save avanavana/c299fcb7e327b872f9ae88d772d2a888 to your computer and use it in GitHub Desktop.
[Algorithms] Selection Sort - Typescript Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file algorithm-selectionSort.ts - A TypeScript implementation of the Selection Sort algorithm | |
* @author Avana Vana | |
* @desc Algorithmic complexity: | |
* - Time complexity: Ω(n^2), Θ(n^2), O(n^2) | |
* - Space complexity: O(1) | |
*/ | |
/** | |
* @function selectionSort | |
* @desc Sorts an input array according to the Selection Sort algorithm and returns the sorted array | |
* @template T | |
* @param {T[]} arr - input array of type T | |
* @returns {T[]} Sorted input array | |
*/ | |
function selectionSort<T>(arr: T[]): T[] { | |
for (let i = 0; i < arr.length; i++) { | |
let smallestItemIndex = i; | |
for (let j = i + 1; j < arr.length; j++) if (arr[j] < arr[smallestItemIndex]) smallestItemIndex = j; | |
if (i !== smallestItemIndex) [ arr[i], arr[smallestItemIndex] ] = [ arr[smallestItemIndex], arr[i] ]; | |
} | |
return arr; | |
} | |
selectionSort([ 3, 7, 5, 2, 6, 1, 0, 4 ]); | |
// > [ 0, 1, 2, 3, 4, 5, 6, 7 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment