Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Why is the swap function not working correctly in quick sort?

I am trying to find an error why quicksort does not work properly, I guess it is because of the swap function

function swap(a, b) {
    return [b,a];
}

function partition(array, l, r) {
    let pivot = array[(l + r) / 2];
    let i = l;
    let j = r;

    while (i <= j) {
        while (array[i] < pivot)
            i++;
        while (array[j] > pivot)
            j++;
        if(i >= j)
            return j;
        [array[i], array[j]] = swap([array[i]], array[j]);
    }
}

function qsort(arr, left, right) {
    if (left < right) {
        let q = partition(arr, left, right)
        qsort(arr, left, q);
        qsort(arr, q + 1, right);
    }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You should pass as a separated variable in swap function

[array[i], array[j]] = swap(array[i], array[j]);

correct solution will be

function swap(array, i, j) {
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

// call it like this
swap(array, index1, index2);
about 4 years ago · Juan Pablo Isaza Report

0

swap does have a problem, at least it should be swap(array[i], array[j]) instead of swap([array[i]], array[j]). but I think your sorting problem Not here, maybe you can try the following


function partition(array, l, r) {
    let pivot = array[l];
    let i = l;
    let j = r;

    while (i < j) {
        while (i < j && array[j] >= pivot) --j;
        arr[i] = arr[j];
        while (i < j && array[i] <= pivot) i++;
        arr[j] = arr[i];
    }
    arr[i] = pivot;
    return i;
}

function qsort(arr, left, right) {
    if (left < right) {
        let q = partition(arr, left, right)
        qsort(arr, left, q-1);
        qsort(arr, q + 1, right);
    }
}

const arr = [1, 7, 9, 8, 3, 2, 6, 0, 5, 4];
qsort(arr, 0, arr.length-1);
console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!