Skip to content

Commit 7b9f82c

Browse files
tusharpamnanipre-commit-ci[bot]tianyizheng02
authored
optimize quicksort implementation (#11196)
* optimize quicksort implementation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply suggestions from code review * Update quick_sort.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
1 parent b46fc1d commit 7b9f82c

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

sorts/quick_sort.py

+13-10
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313

1414

1515
def quick_sort(collection: list) -> list:
16-
"""A pure Python implementation of quick sort algorithm
16+
"""A pure Python implementation of quicksort algorithm.
1717
1818
:param collection: a mutable collection of comparable items
19-
:return: the same collection ordered by ascending
19+
:return: the same collection ordered in ascending order
2020
2121
Examples:
2222
>>> quick_sort([0, 5, 3, 2, 2])
@@ -26,23 +26,26 @@ def quick_sort(collection: list) -> list:
2626
>>> quick_sort([-2, 5, 0, -45])
2727
[-45, -2, 0, 5]
2828
"""
29+
# Base case: if the collection has 0 or 1 elements, it is already sorted
2930
if len(collection) < 2:
3031
return collection
31-
pivot_index = randrange(len(collection)) # Use random element as pivot
32-
pivot = collection[pivot_index]
33-
greater: list[int] = [] # All elements greater than pivot
34-
lesser: list[int] = [] # All elements less than or equal to pivot
3532

36-
for element in collection[:pivot_index]:
37-
(greater if element > pivot else lesser).append(element)
33+
# Randomly select a pivot index and remove the pivot element from the collection
34+
pivot_index = randrange(len(collection))
35+
pivot = collection.pop(pivot_index)
3836

39-
for element in collection[pivot_index + 1 :]:
40-
(greater if element > pivot else lesser).append(element)
37+
# Partition the remaining elements into two groups: lesser or equal, and greater
38+
lesser = [item for item in collection if item <= pivot]
39+
greater = [item for item in collection if item > pivot]
4140

41+
# Recursively sort the lesser and greater groups, and combine with the pivot
4242
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
4343

4444

4545
if __name__ == "__main__":
46+
# Get user input and convert it into a list of integers
4647
user_input = input("Enter numbers separated by a comma:\n").strip()
4748
unsorted = [int(item) for item in user_input.split(",")]
49+
50+
# Print the result of sorting the user-provided list
4851
print(quick_sort(unsorted))

0 commit comments

Comments
 (0)