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&lt;length; i++){ //this loop seems too much

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

            if (array[j] &gt; 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 &lt; 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&lt; 10; i++){ //I used 10 instead of the array length

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

        if (array[j] &gt; array[j+1]){ 

           swap(array, j, j+1);
           }
         }
       }
    };
Let's assume that the input has is a reversed array like  a = 5 4 3 2 1.
every iteration of the outer loop all the 5 - 1 - i smallest elements will be shifted one cell to the right(i is zero in the first iteration) and the 5 - i th element will be moved to the 5 - i th cell. as one can see it takes 4 iteration to sort this.

at every iteration of the outer loop, the n - i th element will be moved to the n - i th cell so it will take at most n - 1 iteration and the worst case (descending array) will always take that many iteration ( the last element will be sorted by itself).