I am working on a program that is designed to showcase how a bubble sort works. However, I would like the program to pause for one second after each swap in order to clearly demonstrate the sorting process. Below is the code I have written:
function bubbleSort(arr){
for(var i = 0; i < arr.length-1; i++){
for(var j = 0; j < arr.length-i-1; j++){
if(arr[j] > arr[j+1]){
swap(arr,j,j+1);
}
}
}
}
Here is the swap function I am using:
async function swap (arr,a,b){
var temp = arr[a];
var temp2 = arr;
temp2[a] = arr[b];
temp2[b] = temp;
await setTimeout(updateText(),1000);
return temp2;
}
This is the updateText function being called:
function updateText(arrayText){
document.getElementById('arrayText').innerHTML = printArray(arr);
}
When I run the bubbleSort() function, I notice that my array goes from unsorted to sorted instantly without showing the individual swaps. The updateText() function is only triggered within the swap function and nowhere else. I would appreciate any assistance or guidance on how to achieve the desired effect of displaying each swap before reaching the final sorted array.