From f15cc7c02c5916cfc0287a70323819df5b08d123 Mon Sep 17 00:00:00 2001 From: Shubham Bhadani Date: Sun, 26 Jul 2020 14:30:40 +0530 Subject: [PATCH] Create InsertionSort.js --- Sorting/InsertionSort.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Sorting/InsertionSort.js diff --git a/Sorting/InsertionSort.js b/Sorting/InsertionSort.js new file mode 100644 index 0000000..ad067a9 --- /dev/null +++ b/Sorting/InsertionSort.js @@ -0,0 +1,21 @@ + +// Insertion sort runs in O(n²), or quadratic, time in the worst case. +// This typically isn’t very effective and should not be used for large lists. +// Because of insertion sort’s low hidden constant value, however, +// it usually outperforms more advanced algorithms such as quick sort or merge sort on smaller lists. + + +let insertionSort = (inputArr) => { + let length = inputArr.length; + for (let i = 1; i < length; i++) { + let key = inputArr[i]; + let j = i - 1; + + while (j >= 0 && inputArr[j] > key) { + inputArr[j + 1] = inputArr[j]; + j = j - 1; + } + inputArr[j + 1] = key; + } + return inputArr; +};