From fa3f0e084f06f345ebb847b8a2035e361a98720b Mon Sep 17 00:00:00 2001 From: Visrut Date: Thu, 28 Jan 2021 23:54:46 +0530 Subject: [PATCH] improved insertion sort with function style (#41) --- sorting/js/insertion-sort.js | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/sorting/js/insertion-sort.js b/sorting/js/insertion-sort.js index a34beff6..57dd52be 100644 --- a/sorting/js/insertion-sort.js +++ b/sorting/js/insertion-sort.js @@ -1,13 +1,16 @@ -let sort = [12,6,3,88,1,4,8]; - -for(let i = 0; i=0){ - sort[j+1]=sort[j]; - j--; +function insertionSort(array) { + // start with index 1 because only one element is already sorted + for(let i=1; i= 0 && array[j] > key) { + array[j+1] = array[j]; + j--; + } + array[j+1] = key; } - sort[j+1]=key; + return array; } -console.log(sort) \ No newline at end of file + +console.log(insertionSort([4,5,6,7,8,10,1,2,3,4])) // output : [1,2,3,4,4,5,6,7,8,10]