Bubblesort problem

I am trying to make a PEN that takes names and ratings, sorts the 2 arrays based on the ratings, using Bubblesort and displays the sorted arrays. But it doesn’t seem to work for numbers greater or equal than 10 (tried 9.99 and it works but not with 10.001 or 10). Here’s the code:

for (var i = numberOfCountries -1; i>=0; i-- ){
  for (var j = 0; j <= i; j++){
    if (ratings[j-1] < ratings[j]){
      var temp = ratings[j-1];
           ratings[j-1] = ratings[j];
           ratings[j] = temp;
      temp = countries[j-1];
      countries[j-1] = countries[j];
      countries[j] = temp;
    }
  }
}

Any suggestions ?

That was the output:

Place #1 i9 with rating 9
Place #2 i8 with rating 8
Place #3 i7 with rating 7
Place #4 i5 with rating 5
Place #5 i10 with rating 10

I inputted in this order :
Country Rating
i5 5
i10 10
i9 9
i7 7
i8 8

Is it a CodePen problem then?

So what do I do to fix the problem? And why doesn’t it work for numbers >=10? It’s so weird…

As @camperextraordinaire said, you’re comparing STRINGS instead of NUMBERS (int, or float).

If you’re comparing strings, “9” < “10” will be false.
While 9 < 10 will be true

For strings, it will be sorted like this
"10"
"11"
"12"
"13"
"2"
"3"
"4"
"5"
“6”

If your array is an integer or float, then it will be sorted like this
2
3
4
5
6
10
11
12
13

Try doing a parseFloat() of the comparison, so you’re comparing the numeric value of your number, instead of the string value.

1 Like