0

I have a program which is supposed to demonstrate a bubble sort, however I want the program to wait one second after every swap to demonstrate what swap is being made. Attached is my code:

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 my swap function:

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;
}

And here is updateText:

function updateText(arrayText){
    document.getElementById('arrayText').innerHTML = printArray(arr);
}

Whenever I execute the bubbleSort() function, my array goes from unsorted to sorted instantly, and does not show the swaps needed to reach the solved array. updateText() is not called anywhere else in my program except for in the swap function. Any help would be greatly appreciated and I can provide clarifications if needed.

  • 4
    The return value from [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) is not a promise. It's the timer ID. – jarmod Jul 29 '22 at 16:03
  • 2
    To follow up on what @jarmod commented, you can do it like this though https://stackoverflow.com/a/51200649/6595385 – blapaz Jul 29 '22 at 16:04
  • The `updateText` doesn't make sense. It takes an argument but doesn't use it, instead it uses a variable `arr` that is not defined in the context. Also, the `setTimeout` is called incorrectly, `setTimeout( updateText() ...` would pass a value returned by the `updateText` to `setTimeout` which is definitely not what you want here. – Wiktor Zychla Jul 29 '22 at 16:35

2 Answers2

1

The issue is the setTimeout function does not return a promise, which await expects.

function resolveAfter1Second() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 1000);
  });
}

async function swap (arr,a,b){
    var temp = arr[a];
    var temp2 = arr;
    temp2[a] = arr[b];
    temp2[b] = temp;
    await resolveAfter1Second();
    return temp2;
}
Ryan
  • 550
  • 4
  • 9
0

Here's an example that simply logs the array to the console. You can replace the console.log(arr) line with a web page update, as needed.

const waitFor = (delay) => new Promise((resolve) => setTimeout(resolve, delay));

async function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        await swap(arr, j, j + 1);
      }
    }
  }
}

async function swap(arr, a, b) {
  [arr[a], arr[b]] = [arr[b], arr[a]]
  console.log(arr);
  return waitFor(1000);
}

const array = [10, 9, 4, 5, 3, 1, 2];
bubbleSort(array);
jarmod
  • 71,565
  • 16
  • 115
  • 122