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
i?-ithen iteration will be low because you have already sorted the elements. If you remove then it will do unwanted operation with sorted elements. You should keep-i