Hello everyone
In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array in this array represents the fully sorted version of the original array. My goal is to update the state and replace the original unsorted array with each value from the array of steps returned by the function;
Below is my insertion sort function:
const insertionSort = (unsortedItems) => {
let sortedList = [...unsortedItems];
let sortingProcess = [];
for (let i = 1; i < sortedList.length; i++) {
let current = sortedList[i];
let j = i - 1;
while (j >= 0 && sortedList[j] > current) {
sortedList[j + 1] = sortedList[j];
j--;
sortingProcess.push(sortedList);
}
sortedList[j + 1] = current;
sortingProcess.push(sortedList);
}
return sortingProcess;
};
export default insertionSort;
Here is where I attempt to update my state:
insertionSort(this.unsortedList).forEach(round =>
setTimeout(() => (this.unsortedList = round), 600)
);
I expected the above code to update my state every 600 ms. However, when clicking the sort button, the array instantly sorts and I do not get to see each step of the sorting process. What could be wrong with my code?