mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Remove Array check and optimise
This commit is contained in:
parent
b5ca4b12e8
commit
ceed279de8
@ -8,32 +8,30 @@ export default class InsertionSort extends Sort {
|
|||||||
for (let i = 0; i < array.length; i += 1) {
|
for (let i = 0; i < array.length; i += 1) {
|
||||||
let currentIndex = i;
|
let currentIndex = i;
|
||||||
|
|
||||||
|
const temp = array[currentIndex];
|
||||||
|
|
||||||
// Call visiting callback.
|
// Call visiting callback.
|
||||||
this.callbacks.visitingCallback(array[i]);
|
this.callbacks.visitingCallback(array[i]);
|
||||||
|
|
||||||
// Go and check if previous elements and greater then current one.
|
// Go and check if previous elements and greater then current one.
|
||||||
// If this is the case then swap that elements.
|
// If this is the case then swap that elements.
|
||||||
while (
|
while (
|
||||||
array[currentIndex - 1] !== undefined
|
currentIndex > 0
|
||||||
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
|
&& this.comparator.lessThan(temp, array[currentIndex - 1])
|
||||||
) {
|
) {
|
||||||
// Call visiting callback.
|
// Call visiting callback.
|
||||||
this.callbacks.visitingCallback(array[currentIndex - 1]);
|
this.callbacks.visitingCallback(array[currentIndex - 1]);
|
||||||
|
|
||||||
// Swap the elements.
|
// Swap the elements.
|
||||||
[
|
array[currentIndex] = array[currentIndex - 1];
|
||||||
array[currentIndex - 1],
|
|
||||||
array[currentIndex],
|
|
||||||
] = [
|
|
||||||
array[currentIndex],
|
|
||||||
array[currentIndex - 1],
|
|
||||||
];
|
|
||||||
|
|
||||||
// Shift current index left.
|
// Shift current index left.
|
||||||
currentIndex -= 1;
|
currentIndex -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
array[currentIndex] = temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
return array;
|
return array;
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user