looking for some solutions? You are welcome.

SOLVED: Bubble sort javascript code need explanation little

NewBie_WannaBe:

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



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent