From ceed279de850dbf34f08d49d0852b6564c748df2 Mon Sep 17 00:00:00 2001 From: = <=> Date: Sat, 17 Oct 2020 20:16:03 +0530 Subject: [PATCH] Remove Array check and optimise --- .../sorting/insertion-sort/InsertionSort.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/algorithms/sorting/insertion-sort/InsertionSort.js b/src/algorithms/sorting/insertion-sort/InsertionSort.js index aa447542..3f7bd55c 100644 --- a/src/algorithms/sorting/insertion-sort/InsertionSort.js +++ b/src/algorithms/sorting/insertion-sort/InsertionSort.js @@ -8,32 +8,30 @@ export default class InsertionSort extends Sort { for (let i = 0; i < array.length; i += 1) { let currentIndex = i; + const temp = array[currentIndex]; + // Call visiting callback. this.callbacks.visitingCallback(array[i]); // Go and check if previous elements and greater then current one. // If this is the case then swap that elements. while ( - array[currentIndex - 1] !== undefined - && this.comparator.lessThan(array[currentIndex], array[currentIndex - 1]) + currentIndex > 0 + && this.comparator.lessThan(temp, array[currentIndex - 1]) ) { // Call visiting callback. this.callbacks.visitingCallback(array[currentIndex - 1]); // Swap the elements. - [ - array[currentIndex - 1], - array[currentIndex], - ] = [ - array[currentIndex], - array[currentIndex - 1], - ]; + array[currentIndex] = array[currentIndex - 1]; // Shift current index left. currentIndex -= 1; } + + array[currentIndex] = temp; } return array; } -} +} \ No newline at end of file