1

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)
    }
}
13
  • Your for loop is incorrect for (var j=0; j++; j < valores.length) should read for (var j=0; j < valores.length; j++) also goes for the inner for loop Commented May 28, 2019 at 22:20
  • for (var j=0; j<valores.length; j++){ for (var i=j+1; i<valores.length; j++) so it should look like this ? spoiler it didn't work Commented May 28, 2019 at 22:23
  • Where is valor defined in your agregarValor function? Commented May 28, 2019 at 22:25
  • 1
    I did debug (kind of) using console.log in all the loops and that's why i noticed it didn't go even into the first one. My teachers here are pretty useless she din't know what was wrong with it. Thanks for your tip! I greatly appreciate it @ug_ Commented May 28, 2019 at 22:56
  • 1
    @ug_ if figured it out. i didn't notice my swap was incorrect because i was reading j as i in my head rookie error. thanks for the help i truly appreciate it, that and the increments were wrong as you also said. in my second loop i was somehow incrementing j again instead of i. I really do appreciate the help :) Commented May 28, 2019 at 23:48

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.