Search code examples
javascriptbubble-sort

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>

Solution

  • 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.