I'm writing a bubble sort program for fun but what i don't understand is
the line j<len-i
does in this code?
i can just remove -i from the above line it will also work,
var arr=[3,5,4,7,8,9,30,0,-1];
function bubble_Sort(arr){
var len = arr.length,
i, j, stop;
for (i=0; i < len; i++){
for (j=0; j<len-i; j++){
if (arr[j] > arr[j+1]){
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
console.log(bubble_Sort(arr));
//with -i in second for loop
var arr=[3,5,4,7,8,9,30,0,-1];
function bubble_Sort(arr){
var len = arr.length,
i, j, stop;
for (i=0; i < len; i++){
for (j=0; j<len-i; j++){
if (arr[j] > arr[j+1]){
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
console.log(bubble_Sort(arr));
Without -i in second loop
Consider the array (to be sorted in increasing order):
[4, 3, 2, 1]
After running your inner loop with i = 0
you will get:
[3, 2, 1, 4]
Now, i=1
...
Repeating the process again, at your next iteration when i=1
you will get:
[2, 1, 3, 4]
Now, i=2
Again, repeating the loop again at i=2
you get:
[1, 2, 3, 4]
Now i=3
Notice how the bold numbers are already in sorted order.
Here we have a loop invariant for the outer loop (ie a statement which holds true for each iteration of the outer loop), which is that the last i
items of the array is in sorted order. Or, another way to look at it is that all items in the array from [0, ... length-i)
are not sorted, and thus items from index length-i
and onwards are in sorted order.
In other words, when you look at your array, you can see that after each iteration of the outer loop, the array all items from length-i, ..., length
are in sorted order, and thus there is no need to re-sort/re-check them.
So, providing the len-i
prevents you from rechecking the items already in sorted order, as you know they won't need to change.