Iterate from 0 to n - i - 1
for ( var j = 0 ; j <= ( n - i - 1 ) ; ++ j ) { if ( arr [ j ] > arr [ j + 1 ] ) { var temp = arr [ j ] ; arr [ j ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; flag = true ; } } if ( flag == false ) break ; } }