I am creating a sorting visualizer. For iterative sorting algorithms, my code works perfectly but for quick sort and merge sort it does not. The function does not wait and immediately returns output but I have to show changes slowly by animations.Following is my code.
const delay = (time) => {
return new Promise((resolve) => setTimeout(resolve, time));
};
const quickSortHelper = async(arr, a, b) => {
if (b > a) {
document.getElementById(a).style.backgroundColor="green"
let pivot = getPivot(arr, a, b)
await delay(2*animationSpeed)
setArray([...arr])
document.getElementById(a).style.backgroundColor="#343434"
await delay(2*animationSpeed)
quickSortHelper(arr, a, pivot - 1)
await delay(4*animationSpeed)
quickSortHelper(arr, pivot + 1, b)
}
}
const quickSort = () => {
setStartSorting(true)
let arr = [...array]
console.log(arr);
quickSortHelper(arr, 0, arr.length - 1)
console.log('ended');
setStartSorting(false)
}
const getPivot = (arr, a, b) => {
let pivot = arr[a]
var i = a
var j = b
while (j > i) {
while (pivot >= arr[i] && i<=b) {
i++
}
while (pivot < arr[j] && j>=a) {
j--
}
if (j > i) {
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
let temp =pivot
arr[a] = arr[j]
arr[j] = temp
return j
}
The console.log(‘ended’) is executed immediately as soon as I run the function and states are also updated immediately.