Search code examples
javascriptsortingbubble-sort

JavaScript bubble sort modification (condition of the loop "for" is not working)


Loop "i" must break, when if statement of loop "j" return swap = false, but it doesn't do that, and proceeding through all of arr.length

bubble sort pen link

var arr = [0, 1, 2, 4, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13];
var n = arr.length;
var t;
var swap;

for (var i = 0; (i < n) && (swap = true); i++) {
for (var j = 0; j < ( n - (i + 1) ); j++) {


    if ( arr[j] > arr[j + 1] ) {

        t = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = t;
        swap = true;

    } else { swap = false }
}
};

Solution

  • this line

    for (var i = 0; (i < n) && (swap = true); i++) {
    

    assigns a value to swap (i.e. swap = true), whereas you actually want to check its value (.i.e. swap === true).

    Note that swap is initially undefined, so if you change your code in line with the above (swap === true) you may want to explicitly set it to true before entering the loop.