Remove Array check and optimise

This commit is contained in:
= 2020-10-17 20:16:03 +05:30
parent b5ca4b12e8
commit ceed279de8

View File

@ -8,30 +8,28 @@ 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;