David Romero
David Romero

Reputation: 53

What's wrong with this bubble-sort function?

I have my array defined but at the moment i go into implement my bubble sorting function it doesn't enter the first for loop. It does run the function however

function bubbleSort (){

    for (var j=0; j++; j < valores.length){
        for (var i=j+1; i++; i < valores.length){
            if (valores[j]>valores[i]){
                var temp=0
                temp=valores[j]
                valores[i]=valores[j]
                valores[j]=temp
            }
        }
    }
    console.log(valores)
}

so if valores input [2,1] I expect the output in console log to be [1,2].

I obtain my array by this function if that is of any help:

let valores =[];
let papelero=10;
function agregarValor (){

    if (valores.length < papelero){

        let val = Number(valor.value)

        valores.push(val)

        console.log(valores)
    }
}

Upvotes: 1

Views: 43

Answers (1)

David Romero
David Romero

Reputation: 53

like @ug_ said my swap was incorrect, and he previously said j and i were incremented in the wrong places.

function bubbleSort() { 
    for (var j=0; j<valores.length; j++) {
        for (var i=j+1; i<valores.length; i++) {
            if (valores[j]>valores[i]) {
                var temp=0
                temp=valores[i]
                valores[i]=valores[j]
                valores[j]=temp
             }
        }
    }
    console.log(valores)
}

Upvotes: 1

Related Questions