Created
December 9, 2016 22:34
-
-
Save zedr/c2e7487f892224efbe218907ea0bac5d to your computer and use it in GitHub Desktop.
Algorithm: zeroes on the right, non-zeroes on left
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
# Given an list of random numbers, push all the zeroes to the end of the list. | |
# For example, if the given list is [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0], | |
# it should be changed to [1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0]. | |
# Time complexity should be O(n). | |
def order(arr): | |
idx = 0 | |
ldx = len(arr) - 1 | |
while idx < ldx: | |
a = arr[idx] | |
b = arr[ldx] | |
if not a: | |
if b: | |
arr[ldx] = a | |
arr[idx] = b | |
idx += 1 | |
ldx -= 1 | |
elif b: | |
if not a: | |
arr[ldx] = a | |
arr[idx] = b | |
ldx -= 1 | |
idx += 1 | |
else: | |
idx += 1 | |
ldx -= 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment