From 53f4db30a786e69265be43c6669b3b0a02e6813c Mon Sep 17 00:00:00 2001 From: Utkarsh Bajpai <64923342+Utkarsh-byte-bot@users.noreply.github.com> Date: Sat, 31 Oct 2020 14:11:44 +0530 Subject: [PATCH] Added Insertion sort in javascript. --- InsertionSort.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 InsertionSort.js diff --git a/InsertionSort.js b/InsertionSort.js new file mode 100644 index 0000000000..40254a4945 --- /dev/null +++ b/InsertionSort.js @@ -0,0 +1,15 @@ +function insertionSort(inputArr) { + let n = inputArr.length; + for (let i = 1; i < n; i++) { + // Choosing the first element in our unsorted subarray + let current = inputArr[i]; + // The last element of our sorted subarray + let j = i-1; + while ((j > -1) && (current < inputArr[j])) { + inputArr[j+1] = inputArr[j]; + j--; + } + inputArr[j+1] = current; + } + return inputArr; +}