Skip to content

Commit 33ffba8

Browse files
authored
Add Dutch National Flag sorting algorithm
Implements the Dutch National Flag algorithm to sort an array of 0s, 1s, and 2s in-place. Includes error handling for invalid values and examples in the docstring.
1 parent 611bad6 commit 33ffba8

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
"""
2+
Implements the Dutch National Flag algorithm to sort an array of 0s, 1s, and 2s
3+
in-place. Includes error handling for invalid values and examples in the docstring.
4+
5+
This algorithm runs in O(n) time and O(1) space using three pointers.
6+
See: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
7+
"""
8+
9+
from __future__ import annotations
10+
11+
12+
def dutch_flag_sort(arr: list[int]) -> None:
13+
"""
14+
Sorts an array of 0s, 1s, and 2s in-place.
15+
16+
Args:
17+
arr: List containing only 0, 1, or 2.
18+
19+
Returns:
20+
None
21+
22+
Raises:
23+
ValueError: If array contains values other than 0, 1, or 2.
24+
25+
Examples:
26+
>>> arr = [2, 0, 2, 1, 1, 0]
27+
>>> dutch_flag_sort(arr)
28+
>>> arr
29+
[0, 0, 1, 1, 2, 2]
30+
31+
>>> arr = [2, 0, 1]
32+
>>> dutch_flag_sort(arr)
33+
>>> arr
34+
[0, 1, 2]
35+
36+
>>> arr = []
37+
>>> dutch_flag_sort(arr)
38+
>>> arr
39+
[]
40+
41+
>>> arr = [1]
42+
>>> dutch_flag_sort(arr)
43+
>>> arr
44+
[1]
45+
46+
>>> arr = [0, 0, 0]
47+
>>> dutch_flag_sort(arr)
48+
>>> arr
49+
[0, 0, 0]
50+
51+
>>> arr = [3]
52+
>>> dutch_flag_sort(arr)
53+
Traceback (most recent call last):
54+
...
55+
ValueError: Array contains invalid value: 3
56+
57+
>>> arr = [-1, 0, 1]
58+
>>> dutch_flag_sort(arr)
59+
Traceback (most recent call last):
60+
...
61+
ValueError: Array contains invalid value: -1
62+
63+
>>> arr = [2, 0, '1']
64+
>>> dutch_flag_sort(arr)
65+
Traceback (most recent call last):
66+
...
67+
ValueError: Array contains invalid value: 1
68+
"""
69+
if not arr:
70+
return
71+
72+
low = mid = 0
73+
high = len(arr) - 1
74+
75+
while mid <= high:
76+
value = arr[mid]
77+
if value == 0:
78+
arr[low], arr[mid] = arr[mid], arr[low]
79+
low += 1
80+
mid += 1
81+
elif value == 1:
82+
mid += 1
83+
elif value == 2:
84+
arr[mid], arr[high] = arr[high], arr[mid]
85+
high -= 1
86+
else:
87+
raise ValueError(f"Array contains invalid value: {value}")
88+
89+
90+
if __name__ == "__main__":
91+
examples = [
92+
([2, 0, 2, 1, 1, 0],),
93+
([2, 0, 1],),
94+
([],),
95+
([1],),
96+
([0, 0, 0],),
97+
([2, 2, 2],),
98+
([1, 1, 1],),
99+
([0, 1, 2, 0, 1, 2],),
100+
([2, 1, 0, 2, 1, 0],),
101+
]
102+
103+
for test_arr in examples:
104+
arr = test_arr.copy()
105+
print(f"Before: {arr}")
106+
dutch_flag_sort(arr)
107+
print(f"After : {arr}\n")

0 commit comments

Comments
 (0)