1

I'm trying to implement quick sort in javascript and need await sleep() inside a function, but when I'm using async the function is not getting correct result.

On removing async from the partition function code is working fine.
Can anyone help?

async function partition(low, high) {
  var pivot = random_numbers[low];  // random_number is a global variable contains 10 random number
  var i = low+1;
  var j = high;

  while (i <= j){
    if (random_numbers[i] < pivot){
        i++;
    }else{
        swap_values(i, j);  // this will swap values in random_numbers
        swap_boxes_sq(i, j);  // this will perform some animation
        await sleep(MAX_SLEEP_TIME); // MAX_SLEEP_TIME = 2000 and sleep is defined in other file
        j--;
    }
  }

  swap_values(low, i-1);      
  return i-1;
}

function sort_q( low, high) {
  if (low < high){
    var pi = partition( low, high);
    sort_q(low, pi-1);
    sort_q(pi+1, high);
  } 
}

function quick_sort(low, high) {
  low = 0;
  high = number_of_box -1;  // number_of_box = 10
  sort_q(low, high);
  console.log(random_numbers);
}
1
  • Can you post the code of sleep() ? Commented Sep 28, 2021 at 11:17

1 Answer 1

1

You made partition asynchronous so you need to add await in sort_q (and make it asynchronous), and add await in quick_sort

The problem is that partition is async, so it returns a Promise. sort_q won't get the correct result for pi if you don't await the result of this Promise.

async function partition(low, high) {
  var pivot = random_numbers[low];  // random_number is a global variable contains 10 random number
  var i = low+1;
  var j = high;

  while (i <= j){
    if (random_numbers[i] < pivot){
        i++;
    }else{
        swap_values(i, j);  // this will swap values in random_numbers
        swap_boxes_sq(i, j);  // this will perform some animation
        await sleep(MAX_SLEEP_TIME); // MAX_SLEEP_TIME = 2000 and sleep is defined in other file
        j--;
    }
  }

  swap_values(low, i-1);      
  return i-1;
}

async function sort_q( low, high) {
  if (low < high){
    var pi = await partition( low, high);
    sort_q(low, pi-1);
    sort_q(pi+1, high);
  } 
}

async function quick_sort(low, high) {
  low = 0;
  high = number_of_box -1;  // number_of_box = 10
  await sort_q(low, high);
  console.log(random_numbers);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.