chore(Python): add dutch national flag algo (#720)

pull/741/head
sam chan 2022-04-11 21:38:45 +08:00 committed by GitHub
parent 38a7cea778
commit dd601a7734
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -6,6 +6,7 @@
- [Rotate Array](arrays/rotate_array.py) - [Rotate Array](arrays/rotate_array.py)
- [Missing Number](arrays/missing_number.py) - [Missing Number](arrays/missing_number.py)
- [Remove duplicate items](arrays/remove_duplicates_list.py) - [Remove duplicate items](arrays/remove_duplicates_list.py)
- [Dutch National Flag Algorithm](arrays/dutch_national_flag_algo.py)
## Linked Lists ## Linked Lists
- [Doubly](linked_lists/doubly.py) - [Doubly](linked_lists/doubly.py)

View File

@ -0,0 +1,39 @@
"""
Algorithm Type: Array sorting with 0s,1s and 2s in a single pass
Explain: To separate three different groups
Time Complexity: O(n)
Space Complexity: O(1)
0 0 1 1 1 ? ? ? ? 2 2
| | |
v v v
Low Mid High
To goal of the algo is to shrink this '?' region
wrapped by Mid and High
> Low starts at 1
"""
numbers = [2, 0, 1, 1, 2, 0, 1, 2]
def DNFS(numbers: list) -> list:
length = len(numbers)
low = 0
high = length - 1
mid = 0
while mid <= high:
if numbers[mid] == 0:
numbers[low], numbers[mid] = numbers[mid], numbers[low]
low = low + 1
mid = mid + 1
elif numbers[mid] == 1:
mid = mid + 1
else:
numbers[mid], numbers[high] = numbers[high], numbers[mid]
high = high - 1
return numbers
if __name__ == "__main__":
print(DNFS(numbers))