Changed swap in QuickSortInPlace and InsertionSort

This commit is contained in:
Gustav Ekner 2022-03-03 20:33:34 +01:00
parent b2427d0e18
commit 822d4e3ac7
2 changed files with 7 additions and 15 deletions

View File

@ -6,7 +6,7 @@ export default class InsertionSort extends Sort {
// Go through all array elements...
for (let i = 1; i < array.length; i += 1) {
let currentIndex = i;
let j = i;
// Call visiting callback.
this.callbacks.visitingCallback(array[i]);
@ -14,23 +14,17 @@ export default class InsertionSort extends Sort {
// Check if previous element is greater than current element.
// If so, swap the two elements.
while (
array[currentIndex - 1] !== undefined
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
array[j - 1] !== undefined
&& this.comparator.lessThan(array[j], array[j - 1])
) {
// Call visiting callback.
this.callbacks.visitingCallback(array[currentIndex - 1]);
this.callbacks.visitingCallback(array[j - 1]);
// Swap the elements.
[
array[currentIndex - 1],
array[currentIndex],
] = [
array[currentIndex],
array[currentIndex - 1],
];
[array[j - 1], array[j]] = [array[j], array[j - 1]];
// Shift current index left.
currentIndex -= 1;
j -= 1;
}
}

View File

@ -39,9 +39,7 @@ export default class QuickSortInPlace extends Sort {
* @param {number} rightIndex
*/
const swap = (leftIndex, rightIndex) => {
const temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
[array[leftIndex], array[rightIndex]] = [array[rightIndex], array[leftIndex]];
};
const pivot = array[highIndex];