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);
}
}
}
};