Skip to content

Commit

Permalink
feat: dutch national flag problem
Browse files Browse the repository at this point in the history
  • Loading branch information
ashwin-nair98 committed Mar 6, 2024
1 parent a8e8a79 commit 305f2e9
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions elements/5_1_Dutch_National_Flag/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Question: Partition an array A with a pivot i such that all A[x] <= A[i] appears first


def partition(arr, i):
start = 0
pivot = arr[i]
for j in range(len(arr)):
while start < len(arr) and arr[start] < pivot:
start += 1
if start >= len(arr):
break
if arr[j] <= pivot:
arr[start], arr[j] = arr[j], arr[start]
start += 1
return arr


# Test
def expect(a, b):
result = a == b
print("Test for " + str(a) + (" passed!" if result else " failed!"))


a = [0, 1, 2, 0, 2, 1, 1]
i = 3
res = [0, 0, 1, 2, 2, 1]

expect(a, partition(a, i))

0 comments on commit 305f2e9

Please sign in to comment.