Skip to content

Commit 7c9b6a8

Browse files
authored
Add quick_sort and 3-way quick_sort with tests
1 parent c3d4b9e commit 7c9b6a8

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

sorts/quick_sort_with_tests.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from typing import List, Optional
2+
3+
4+
def quick_sort(arr: List[int]) -> List[int]:
5+
"""
6+
Classic quick sort implementation using list comprehensions.
7+
8+
Args:
9+
arr (List[int]): List of integers to sort.
10+
11+
Returns:
12+
List[int]: New sorted list.
13+
"""
14+
if len(arr) <= 1:
15+
return arr
16+
else:
17+
pivot = arr[len(arr) // 2]
18+
left = [x for x in arr if x < pivot]
19+
middle = [x for x in arr if x == pivot]
20+
right = [x for x in arr if x > pivot]
21+
return quick_sort(left) + middle + quick_sort(right)
22+
23+
24+
def quick_sort_3way(arr: List[int], low: int = 0, high: Optional[int] = None) -> List[int]:
25+
"""
26+
In-place 3-way partitioning quick sort.
27+
28+
Args:
29+
arr (List[int]): List of integers to sort.
30+
low (int): Starting index of the sublist to sort.
31+
high (Optional[int]): Ending index of the sublist to sort.
32+
33+
Returns:
34+
List[int]: The same list sorted in-place.
35+
"""
36+
if high is None:
37+
high = len(arr) - 1
38+
39+
if low < high:
40+
lt, gt = low, high
41+
pivot = arr[low]
42+
i = low + 1
43+
44+
while i <= gt:
45+
if arr[i] < pivot:
46+
arr[lt], arr[i] = arr[i], arr[lt]
47+
lt += 1
48+
i += 1
49+
elif arr[i] > pivot:
50+
arr[i], arr[gt] = arr[gt], arr[i]
51+
gt -= 1
52+
else:
53+
i += 1
54+
55+
quick_sort_3way(arr, low, lt - 1)
56+
quick_sort_3way(arr, gt + 1, high)
57+
58+
return arr
59+
60+
61+
def test_quick_sorts():
62+
"""
63+
Simple test cases for quick_sort and quick_sort_3way functions.
64+
"""
65+
test_cases = [
66+
([3, 6, 8, 10, 1, 2, 1], [1, 1, 2, 3, 6, 8, 10]),
67+
([4, 5, 4, 3, 4, 2, 1, 4], [1, 2, 3, 4, 4, 4, 4, 5]),
68+
([], []),
69+
([1], [1]),
70+
([2, 1], [1, 2]),
71+
]
72+
73+
for i, (input_arr, expected) in enumerate(test_cases):
74+
assert quick_sort(input_arr) == expected, f"quick_sort failed on test case {i + 1}"
75+
assert quick_sort_3way(input_arr.copy()) == expected, f"quick_sort_3way failed on test case {i + 1}"
76+
77+
print("All tests passed!")
78+
79+
80+
if __name__ == "__main__":
81+
test_quick_sorts()

0 commit comments

Comments
 (0)