Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda