Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Created February 10, 2020 05:34
Show Gist options
  • Save drem-darios/9ce4d841b5067475ae67bd7c58eab40a to your computer and use it in GitHub Desktop.
Save drem-darios/9ce4d841b5067475ae67bd7c58eab40a to your computer and use it in GitHub Desktop.
Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array.
def dutch_flag_sort(arr):
n = len(arr)
frontPointer = 0
backPointer = n - 1
solutionIndex = 0
while solutionIndex <= backPointer:
# Swap the 0s
if arr[solutionIndex] == 0:
swap(solutionIndex, frontPointer, arr)
frontPointer +=1
solutionIndex +=1
# Go over 1s
elif arr[solutionIndex] == 1:
solutionIndex +=1
else:
swap(solutionIndex, backPointer, arr)
backPointer -=1
def swap(f_pointer, b_pointer, arr):
temp = arr[b_pointer]
arr[b_pointer] = arr[f_pointer]
arr[f_pointer] = temp
return
def main():
arr = [1, 0, 2, 1, 0]
dutch_flag_sort(arr)
print(arr)
arr = [2, 2, 0, 1, 2, 0]
dutch_flag_sort(arr)
print(arr)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment