From b4346f95661a348cbc4dcb97c7f599a25708b5cd Mon Sep 17 00:00:00 2001 From: Rahul Saini <111075975+Rahul-K-Saini@users.noreply.github.com> Date: Tue, 2 Jan 2024 15:00:14 +0530 Subject: [PATCH] Create InsertionSort.js Added Insertion Sort --- Algorithms/InsertionSort.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Algorithms/InsertionSort.js diff --git a/Algorithms/InsertionSort.js b/Algorithms/InsertionSort.js new file mode 100644 index 0000000..afcfb66 --- /dev/null +++ b/Algorithms/InsertionSort.js @@ -0,0 +1,20 @@ +function insertionSort(arr) { + const n = arr.length; + + for (let i = 1; i < n; i++) { + let currentElement = arr[i]; + let j = i - 1; + + while (j >= 0 && arr[j] > currentElement) { + arr[j + 1] = arr[j]; + j--; + } + + arr[j + 1] = currentElement; + } +} + +// Example usage: +var arr = [7, 2, 1, 6, 5, 3, 8, 4]; +insertionSort(arr); +console.log(arr.toString());