Skip to content

Commit 15bddee

Browse files
authored
Update quicksort.py
1 parent d5e4b7a commit 15bddee

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

divide_and_conquer/quicksort.py

+34-6
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
11
from __future__ import annotations
22

3-
43
def partition(array: list, low: int, high: int) -> int:
5-
"""Helper function for quicksort to partition the array.
4+
"""
5+
Helper function for quicksort to partition the array.
6+
67
>>> array = [3, 2, 1]
7-
>>> partition(array, 0, len(array) - 1)
8+
>>> idx = partition(array, 0, len(array) - 1)
9+
>>> idx
810
0
911
>>> array
1012
[1, 2, 3]
13+
1114
>>> array = [12, 4, 5, 2, 3]
1215
>>> idx = partition(array, 0, len(array) - 1)
1316
>>> array[:idx], array[idx], array[idx+1:]
1417
([2, 3, 4], 5, [12])
18+
19+
>>> array = [2, 1]
20+
>>> idx = partition(array, 0, len(array) - 1)
21+
>>> array
22+
[1, 2]
1523
"""
1624
pivot = array[high]
1725
i = low - 1 # Pointer for the smaller element
@@ -24,18 +32,38 @@ def partition(array: list, low: int, high: int) -> int:
2432
array[i + 1], array[high] = array[high], array[i + 1]
2533
return i + 1
2634

27-
2835
def quicksort(array: list, low: int = 0, high: int | None = None) -> list:
36+
"""
37+
Returns a sorted list using the quicksort algorithm.
38+
39+
>>> quicksort([-2, 3, -10, 11, 99, 100000, 100, -200])
40+
[-200, -10, -2, 3, 11, 99, 100, 100000]
41+
42+
>>> quicksort([1, 2, 3, 4, 5])
43+
[1, 2, 3, 4, 5]
44+
45+
>>> quicksort([5, 4, 3, 2, 1])
46+
[1, 2, 3, 4, 5]
47+
48+
>>> quicksort([-200])
49+
[-200]
50+
51+
>>> quicksort([])
52+
[]
53+
54+
>>> quicksort([10000000, 1, -1111111111, 101111111112, 9000002])
55+
[-1111111111, 1, 9000002, 10000000, 101111111112]
56+
"""
2957
if high is None:
3058
high = len(array) - 1
59+
3160
if low < high:
3261
pivot_index = partition(array, low, high)
3362
quicksort(array, low, pivot_index - 1)
3463
quicksort(array, pivot_index + 1, high)
35-
return array
3664

65+
return array
3766

3867
if __name__ == "__main__":
3968
import doctest
40-
4169
doctest.testmod()

0 commit comments

Comments
 (0)