1

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);

});
2
  • Looks like it's sorting correctly. Why do you think it's only "part" of the array? Commented Dec 15, 2019 at 14:44
  • 1
    Change to var blocks = [50, 90, 70, 40, 190, 110, 300, 30, 60, 245]; - what do you get? Do you know why it's different? Commented Dec 15, 2019 at 14:45

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.