Skip to content

Instantly share code, notes, and snippets.

@zedr
Created December 9, 2016 22:34
Show Gist options
  • Save zedr/c2e7487f892224efbe218907ea0bac5d to your computer and use it in GitHub Desktop.
Save zedr/c2e7487f892224efbe218907ea0bac5d to your computer and use it in GitHub Desktop.
Algorithm: zeroes on the right, non-zeroes on left
# 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