Search code examples
javascriptalgorithmsortingbubble-sort

Bubble Sort algo sorting items in descending order - JavaScript


Following is my code for bubble sort, which is sorting the array in descending only. However I am trying it to sort by ascending only. Please let me know where I am doing wrong.

var a = [53, 11, 34, 12, 18];

for(var i = 0; i < a.length; i++) {
    for(var j=0; j < a.length; j++) {
        if(a[i] > a[j]) {
            var temp = a[i];
            a[i] = a[j];
            a[j] = temp;        
        }
    }
}

console.log("Array:: ", a);

Solution

  • In a proper bubble sort, the inner loop should not iterate all values each time. Your inner loop must start at i+1:

    for(var j=i+1; j < a.length; j++) {
    

    var a = [53, 11, 34, 12, 18];
    
    for(var i = 0; i < a.length; i++) {
        for(var j=i+1; j < a.length; j++) {
            if(a[i] > a[j]) {
                var temp = a[i];
                a[i] = a[j];
                a[j] = temp;        
            }
        }
    }
    
    console.log("Array:: ", a);