Search code examples
javascripthtmlbubble-sort

Bubble Sort Is only sorting my numbers halfway why? JS and HTML


I am sorting 30 random generated number by a bubble sort for some reason they get sorted from 15 to 29 but they are still not sorted from 0 to 14. It is like the sorting stops for some reason. My attempt was to change i++ to i-- but didn't really work. Does anyone know what's wrong in the loop thank you

JavaScript:

arr =new Array(30);
var length = arr.length;

function randomNumber(min,max){
    var min = Math.ceil(min);
    var max = Math.floor (max);
        for(var i = 0; i<length; i++){
            arr[i] = Math.floor(Math.random() * (max-min)) + min;
            document.write("Number " +(i)+ " : "   +arr[i] + "<br >"); }

    for (var i = 0; i < arr.length; i++) { 
      for (var j = 0; j < arr.length; j++) { 
        
        if (arr[j] > arr[j + 1]){
          //Swap the numbers
         var tmp = arr[j]; 
          arr[j] = arr[j + 1]; 
        arr[j + 1] = tmp; //Replace adjacent number with current number       
        //[[arr[j],arr[j+1]] = [arr[j+1], arr[j]]];} }
      document.write("Number " +(i)+ " : "   +arr[i] + "<br >"); }
    return arr;}

HTML calling the method:

                            <script> 
                                  
                                randomNumber(1,1000);

                            </script> 

Below are outputs of the code:

Random Numbers

Bubble Sort


Solution

  • Don't print out the array within the loop. The sorting process isn't finished yet. Move the write command after it.

    for (var i = 0; i < arr.length; i++) { 
        for (var j = 0; j < arr.length; j++) { 
            if (arr[j] > arr[j + 1]) {
                var tmp = arr[j]; 
                arr[j] = arr[j + 1]; 
                arr[j + 1] = tmp; 
            }
        }
    }
    for (var i = 0; i<length; i++) {
        document.write("Number " +(i)+ " : "   +arr[i] + "<br >");     
    }
    

    It should give you the right answer.