# Is the outer loop in typical bubble sort algorithm precise?

I analized the bubble sort algorithm and I cannot see why they "implemented this way". I wrote down the results as the two loops performed their works and, with my small testing arrays, the outer loop condition to stop was always too much (the array was sorted when "i" was like 2, when the loop conditon to stop was 5.

this.bubbleSort = function(){
var length = array.length;

for (var i=0; i<length; i++){ //this loop seems too much

for (var j=0; j<length-1; j++ ){

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

swap(array, j, j+1);
}
}
}
};


Is there a possibility that the outer loop will have to reach its limit? I mean the "i - 1 < length" will be necessary to sort. Is the array length on the outer loop really a precise choice or just a good choice, because it gives a clue of how many inner loop iterations will be needed with some leftover if necessary?

For me it means that the algorithm could be written, somehow, like this

var length = array.length;

for (var i=0; i< 10; i++){ //I used 10 instead of the array length

for (var j=0; j<length-1; j++ ){

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

swap(array, j, j+1);
}
}
}
};

• If no swap is done in the inner loop, the outer loop can stop. (That's how I was taught bubble sort many years ago, too.) In fact, you can optimise further by using the index of the first swap as the start index of the next iteration. No matter what optimisations you find, bubblesort is quadratic and just about any other non-pathological sort algorithm is better. – rici May 16 '18 at 7:30