Created
February 16, 2018 21:07
-
-
Save edtoken/564234f5c8405cdd9bdfe342fcf2cc77 to your computer and use it in GitHub Desktop.
Move all zeros to end.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function moveZeros(array) { | |
let i = 0; | |
let len = array.length; | |
let s = undefined; | |
let e = undefined; | |
while(i < len){ | |
if(!array[i]){ | |
if(s == undefined){ | |
s = i; | |
e = i; | |
}else{ | |
e = i; | |
} | |
i++; | |
continue; | |
} | |
if(s != undefined){ | |
array[s] = array[i]; | |
array[i] = 0; | |
i--; | |
if(s < e){ | |
s ++; | |
}else{ | |
s = undefined; | |
e = undefined; | |
} | |
} | |
i++; | |
} | |
return array; | |
} | |
alert(moveZeros([0,1,4,0,0,0,2,2,2,2,2,0,0,10])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment