Skip to content

Commit dc7c493

Browse files
authored
Update quick_sort.py
Updated the algorithm to do in-place storage, leading to efficient space management
1 parent 40f65e8 commit dc7c493

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

sorts/quick_sort.py

+20-3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@ def quick_sort(collection: list) -> list:
1919
:param collection: a mutable collection of comparable items
2020
:return: the same collection ordered in ascending order
2121
22+
Time Complexity:
23+
Best Case: O(n log n)
24+
Average case: O(n log n)
25+
Worst Case: O(n^2)
26+
27+
Space Complexity:
28+
Best Case: O(log n) for In-place implementation
29+
Worst Case: O(n)
30+
2231
Examples:
2332
>>> quick_sort([0, 5, 3, 2, 2])
2433
[0, 2, 2, 3, 5]
@@ -35,10 +44,18 @@ def quick_sort(collection: list) -> list:
3544
pivot_index = randrange(len(collection))
3645
pivot = collection.pop(pivot_index)
3746

38-
# Partition the remaining elements into two groups: lesser or equal, and greater
39-
lesser = [item for item in collection if item <= pivot]
40-
greater = [item for item in collection if item > pivot]
47+
# Initialise empty lists to store the elements
48+
49+
lesser = [] # Stores elements less than or equal to the pivot
50+
greater = [] # Stores elements greater than the pivot
4151

52+
# Loop through the collections and partition
53+
for item in collection:
54+
if item <= pivot:
55+
lesser.append(item)
56+
else:
57+
greater.append(item)
58+
4259
# Recursively sort the lesser and greater groups, and combine with the pivot
4360
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
4461

0 commit comments

Comments
 (0)