# Implement Bubble Sort. What's the flaw in my logic?

Tell us what’s happening:

``````
function bubbleSort(array) {
// change code below this line
const length = array.length-1;
let tmp = 0;

for(let i=0; i<length; i++) {
let swapped = false;
if(array[i] < array[i+1]){
tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
swapped = true;
}

if(swapped) i = 0;
}

// change code above this line
console.log(array)
return array;
}

// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
bubbleSort( [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92])
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36`.

https://learn.freecodecamp.org/coding-interview-prep/algorithms/implement-bubble-sort

``````for(let i=0; i<length; i++)
``````

If `length` is `array.length - 1`, then the loop condition should be `i <=length`.

Also, consider having a loop inside of your loop instead of using `swapped`.

1 Like