Skip to content

Commit e8f2e4a

Browse files
authored
Update quicksort.py
1 parent 4a911e3 commit e8f2e4a

File tree

1 file changed

+13
-44
lines changed

1 file changed

+13
-44
lines changed

divide_and_conquer/quicksort.py

+13-44
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,12 @@
11
from __future__ import annotations
22

3-
4-
def partition(array: list, low: int, high: int) -> int:
5-
"""
6-
Helper function for quicksort to partition the array.
7-
8-
>>> array = [3, 2, 1]
9-
>>> idx = partition(array, 0, len(array) - 1)
10-
>>> idx
11-
0
12-
>>> array
13-
[1, 2, 3]
14-
15-
>>> array = [12, 4, 5, 2, 3]
16-
>>> idx = partition(array, 0, len(array) - 1)
17-
>>> array[:idx], array[idx], array[idx+1:]
18-
([2, 3, 4], 5, [12])
19-
20-
>>> array = [2, 1]
21-
>>> idx = partition(array, 0, len(array) - 1)
22-
>>> array
23-
[1, 2]
24-
"""
25-
pivot = array[high]
26-
i = low - 1 # Pointer for the smaller element
27-
28-
for j in range(low, high):
29-
if array[j] <= pivot:
30-
i += 1
31-
array[i], array[j] = array[j], array[i]
32-
33-
array[i + 1], array[high] = array[high], array[i + 1]
34-
return i + 1
35-
36-
37-
def quicksort(array: list, low: int = 0, high: int | None = None) -> list:
3+
def quicksort(array: list) -> list:
384
"""
395
Returns a sorted list using the quicksort algorithm.
406
7+
Quicksort uses a divide-and-conquer approach to sort the elements
8+
by selecting a pivot and partitioning the array.
9+
4110
>>> quicksort([-2, 3, -10, 11, 99, 100000, 100, -200])
4211
[-200, -10, -2, 3, 11, 99, 100, 100000]
4312
@@ -55,19 +24,19 @@ def quicksort(array: list, low: int = 0, high: int | None = None) -> list:
5524
5625
>>> quicksort([10000000, 1, -1111111111, 101111111112, 9000002])
5726
[-1111111111, 1, 9000002, 10000000, 101111111112]
58-
"""
59-
if high is None:
60-
high = len(array) - 1
6127
62-
if low < high:
63-
pivot_index = partition(array, low, high)
64-
quicksort(array, low, pivot_index - 1)
65-
quicksort(array, pivot_index + 1, high)
28+
>>> quicksort([2, 1])
29+
[1, 2]
30+
"""
31+
if len(array) <= 1:
32+
return array
6633

67-
return array
34+
pivot = array[-1] # Choose the last element as the pivot
35+
left = [x for x in array[:-1] if x <= pivot]
36+
right = [x for x in array[:-1] if x > pivot]
6837

38+
return quicksort(left) + [pivot] + quicksort(right)
6939

7040
if __name__ == "__main__":
7141
import doctest
72-
7342
doctest.testmod()

0 commit comments

Comments
 (0)