Reputation: 37
I am trying to use bubble sort to sort this array,
var blocks = ["50", "90", "70", "40", "190", "110", "300", "30", "60", "245"];
But for some reason I only get 110,190,245,30,300,40,50,60,70,90 when I print out the array after sorting.
Here is the code for sorting
$("#bubble").click(function(){
for(var i=0; i<blocks.length; i++){
for(var j=0; j<blocks.length-i-1; j++){
if(blocks[j]> blocks[j+1]){
var temp = blocks[j];
blocks[j] = blocks[j+1];
blocks[j+1] = temp;
}
}
}
var x = blocks.toString();
$("#blocks_container").append(x);
});
Upvotes: 1
Views: 170
Reputation: 38144
Sorting algorithm is okay. However, you are comparing string
values and this is a reason why you've got unexpected result.
However, you can convert your string
to int
using +
sign and map
function:
blocks = blocks.map(b => +b);
And then sorting will be done correctly:
var blocks = ["50", "90", "70", "40", "190", "110", "300", "30", "60", "245"];
const bubbleSort = (blocks) => {
blocks = blocks.map(b => +b);
for (var i = 0; i < blocks.length; i++) {
for (var j = 0; j < blocks.length - i - 1; j++) {
if (blocks[j] > blocks[j + 1]) {
var temp = blocks[j];
blocks[j] = blocks[j + 1];
blocks[j + 1] = temp;
}
}
}
return blocks;
}
console.log(bubbleSort(blocks));
Upvotes: 0
Reputation: 192132
You are sorting strings and not numbers. When comparing by their lexical values, the 1st characters are compared, and if they are the same, the 2nd characters are compared, and so on. In this case 100
is "less" than 20
, since 1
comes before 2
.
If you want to compare the items by their numeric values, cast them to numbers using the +
operator:
+blocks[j] > +blocks[j + 1]
Example:
var blocks = ["50", "90", "70", "40", "190", "110", "300", "30", "60", "245"];
for (var i = 0; i < blocks.length; i++) {
for (var j = 0; j < blocks.length - i - 1; j++) {
if (+blocks[j] > +blocks[j + 1]) {
var temp = blocks[j];
blocks[j] = blocks[j + 1];
blocks[j + 1] = temp;
}
}
}
console.log(blocks);
Upvotes: 3