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