javascript - Execution stops after the first iteration of the outter loop -


var array = [5,3,4,1]  for(var x = 0; x < array.length; x++){      for(var y = array.length - 1; y >= x; y--){          if(array[x] > array[y]){           var temp = array[y];           array[y] = array[x];           array[x] = temp;      }   } } console.log(array);   //output : [1,3,4,5] 

i understand loops meant swap loops swapping 2 values if x greater y.

[1,3,4,5] result when x = 0, why doesn't change once x = 1, , on? shouldn't secondary for-loop run thru iterations , continue swap values until first loop reaches array.length (4)?

edit: bit more information on thought process is: output [1,3,4,5] after first iteration, when iterates x = 1? @ point, x[1] = 3, correct? if statement fails when y decrements 5, 4, 3, 3 > 1 , think output changed [3,1,4,5]. @ point x iterates x[2] 4 , output becomes [4,3,1,5] , finally, x[3] = 5 no further swaps possible

var array = [5,3,4,1] for(var x = 0; x < array.length; x++){     for(var y = array.length - 1; y >= x; y--){             console.log("condition="+(array[x] > array[y]));          if(array[x] > array[y]){           var temp = array[y];           array[y] = array[x];           array[x] = temp;      }   } } console.log(array);  

if @ code above trying swapping value based on condition array[x] > array[y]. means whenever condition true values swapped. code have total 10 iterations. condition evaluated 10 times in particular code. , out of ten time true once. rest 9 time evaluated false. swapping logic wont executed 9 times output [1, 3, 4, 5] mentioned after first iteration. in above code have put console.log("condition="+(array[x] > array[y])); understand when condition evaluates true , swapping happens.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -