JS Bubblesort problem

Hi guys,

I am learning Javascript and trying to program a bubblesort. Does anyone know, what is wrong with this code?
It just functions partly …

function sort(ar){

for ( var i=0; i < ar.length-1; i++){

if(ar[i] > ar[i+1]){

var remember = ar[i] ;
ar[i+1] =remember;


return ar;

Thanks a lot in advance!


Hi Mona,
What you have done is a first pass. You have insured that the last item in the array is indeed the largest - you have “bubbled” the largest element up to the “top”. You now need to do the same for the remainder of the array.

For instance, if sorting [5, 4, 3, 2, 1] your function would return [ 4, 3, 2, 1, 5 ]. 5 is now in it’s proper place. The rest of the array still needs to be sorted.

You will have to do much the same again to “bubble” the next largest up to it’s place, then the next largest and so on.

As you progress, more items at the end of the array will be in their proper place so there will be no need to sort those. Using same example after first pass you have [ 4, 3, 2, 1, 5 ] so on the second pass there is no reason to check the last index because you already know that is in it’s place. After the second pass you will be sure of the position of the last two items of the array and so on.

Each pass will get you closer to a fully sorted array.
[ 4, 3, 2, 1, 5 ]
[ 3, 2, 1, 4, 5 ]
[ 2, 1, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

Hi alhazen1,

thanks a lot for your response. I did it know :slight_smile: