Answer the question
In order to leave comments, you need to log in
JS loop and array question - why is that?
Why does i-1 work in a nested loop, even without -1?
function bubbleSort(arr){
var noSwaps;
for(var i = arr.length; i > 0; i--){
noSwaps = true;
for(var j = 0; j < i - 1; j++){
console.log(arr, arr[j], arr[j + 1], 'i and j', i, j); //
if(arr[j] > arr[j+1]){
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
noSwaps = false;
}
}
if(noSwaps) break;
}
return arr;
}
alert(bubbleSort([8,1,2, 9]));
Answer the question
In order to leave comments, you need to log in
Because arr[j] is compared to arr[j+1]. These are two elements in a row. This means that j should not go from 0 to the maximum, but from 0 to the maximum minus 1.
If we make the condition j < i, then there will be an extra operation that is not needed, although it does not interfere. We just have a sorted array from i to arr.length. Therefore, a[j+1] will be equal to a[i], but a[i] is already exactly in its place and there is no need to move it anywhere. Therefore, this is just an extra operation, for which arr[j] > arr[j+1] will obviously be false.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question