简体   繁体   中英

Why is this happening? (Bubble Sort) [JavaScript]

I'm currently having a bit of a problem with a bubble sort program in JavaScript, the problem I seem to have is that for example when I give my Array values from 1 - 10 it organizes them like this: 1,10,2,3,4,5,6,7,8,9.

Here's my code:

function bubble(){

var array = [10];
var j=0;
var i=0;

for(i=0; i<10; i++){

array[i] = prompt("Inset a Number");

}
  for (i=0; i < 10; i++){

    for (j=0; j < 10; j++){

        if(array[j+1] < array[j]){

            temp = array[j];
            array[j] = array[j+1];
            array[j+1] = temp;
        }
    }
   }

alert(array);

}
    </script>

It is treating the data as a string and sorting properly. You need to parseInt() your input from the prompt(), or just subtract 0. For example, prompt("Inset a Number")-0.

The numbers are actually strings because prompt value is returned as a string. You need to convert the string to an int like this:

array[i] = parseInt(prompt("Inset a Number"));

You are currently comparing strings. Because prompt will return a string, it needs to be converted to an int before you can compare it correctly.

array[i] = parseInt(prompt("Inset a Number"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM