From b7be24f4c60bc209c4b04dec96b271ab1b9a0d64 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:52:15 +1000 Subject: [PATCH] Algorithms: Implement Selection Sort --- Algorithms/selectionSort.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Algorithms/selectionSort.js diff --git a/Algorithms/selectionSort.js b/Algorithms/selectionSort.js new file mode 100644 index 0000000..ea2516a --- /dev/null +++ b/Algorithms/selectionSort.js @@ -0,0 +1,22 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-selection-sort + +function selectionSort(array) { + // Only change code below this line + const swap = (array, indexA, indexB) => { + const temp = array[indexA]; + array[indexA] = array[indexB]; + array[indexB] = temp; + }; + + for (let i = 0; i < array.length; i++) { + let minIndex = i; + for (let j = i; j < array.length; j++) { + if (array[j] < array[minIndex]) { + minIndex = j; + } + swap(array, i, minIndex); + } + } + return array; + // Only change code above this line +}