Search code examples
javascriptbubble-sort

Why does My Bubble sort code always show me repeated numbers?


Recenly I tried to test my own Bubble Sort code using JavaScript but the problem is everytime I run it the output still show me the same result. It repeatedly print the last index in the array. Can anyone help me out, I'm still new at this.

By the way here's the code.

var num = [31,23,55,2,13,90];
var bilnum = num.length,i ,j;
var temp = num[0];

for(i = 0;i < bilnum; i++){
    for(j = 0 ;j < bilnum - i; j++){
        if(num[j] < num[j+1]){
            num[j] = temp;
            num[j] = num[j+1];
            temp = num[j];
            
        }
    }
}

document.write(num)

Solution

  • Your problem is here:

    for(i = 0;i < bilnum; i++){
      for(j = 0 ;j < bilnum - i; j++){
          if(num[j] < num[j+1]){
              num[j] = temp;
              num[j] = num[j+1];
              temp = num[j];
          }
      }
    }
    

    When you switch, who is temp at first? It is your first value (temp = num[0] in the beginning). It then takes the value of the first swap and so on, messing up your array and outputting the unexpected result.

    When switching two elements, the order is like this:

    temp = num[j] -> hold current value

    num[j] = num[j + 1] -> swap with the next value

    num[j + 1] = temp -> put the value from before in the new position

    Also, your if condition will sort your array in descending order. Use: if (arr[j] > arr[j + 1]) to sort in increasing order

    Your final code should look like this:

    var num = [31,23,55,2,13,90];
    var bilnum = num.length,i ,j;
    var temp;
    
    for(i = 0;i < bilnum; i++){
        for(j = 0 ;j < bilnum - i; j++){
            if(num[j] > num[j+1]){
                num[j] = temp;
                num[j] = num[j+1];
                temp = num[j];
            
            }
        }
     }
    
     document.write(num)