I am making a sorting visualiser and I've already completed it for bubble, insertion and selection. I am facing a problem with merge sort because it involves recursion and there seems to be some issue in updating the state variable.
async function mergeSort(arr, setArr, mainArray) {
let n = arr.length;
if (n === 1) {
return arr;
}
let leftArray = arr.slice(0, Math.floor(n / 2));
let rightArray = arr.slice(Math.floor(n / 2), n);
leftArray = await mergeSort(leftArray, setArr, mainArray);
rightArray = await mergeSort(rightArray, setArr, mainArray);
let mergeResultArray = await merge(leftArray, rightArray);
let l = mergeResultArray.length;
let tempArr = [...mergeResultArray];
let copyArr = [...mainArray];
let subArr = copyArr.slice(l, mainArray.length);
tempArr.push(...subArr);
setArr(JSON.parse(JSON.stringify(tempArr)));
return mergeResultArray;
}
async function merge(array1, array2) {
let array3 = [];
while (array1.length && array2.length) {
await delay(DELAY);
if (array1[0].val > array2[0].val) {
array3.push(array2[0]);
array2.splice(0, 1);
} else {
array3.push(array1[0]);
array1.splice(0, 1);
}
}
while (array1.length) {
await delay(DELAY);
array3.push(array1[0]);
array1.splice(0, 1);
}
while (array2.length) {
await delay(DELAY);
array3.push(array2[0]);
array2.splice(0, 1);
}
return array3;
}
const delay = (DELAY) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("");
}, DELAY);
});
};
setArr is the function returned by useState to update the array on the main component which is being passed to the function. The part after await merge() is just to create the current mainArray after merging the parts after each step to visualise the intermediate steps.
Right now what's happening is that after the function is called, the main component goes blank where the array is supposed to be and after some time, it appears and it is completely sorted. The intermediate setArr() are not showing on the component.
After learning that setArr(arr) takes significant time (laziness) (because it was delayed in other sorting algorithms as well), I used JSON.parse(JSON.stringify()) to render it immediately.
What could be the issue and how do I fix this to show all intermediate steps ?
Also, I'm getting this error
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at Bar (http://localhost:3000/static/js/main.chunk.js:281:13) at li
if it helps