Skip to content

Update quick_sort.py #11752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions sorts/quick_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ def quick_sort(collection: list) -> list:
:param collection: a mutable collection of comparable items
:return: the same collection ordered in ascending order

Time Complexity:
Best Case: O(n log n)
Average case: O(n log n)
Worst Case: O(n^2)

Space Complexity:
Best Case: O(log n) for In-place implementation
Worst Case: O(n)

Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
Expand All @@ -35,9 +44,17 @@ def quick_sort(collection: list) -> list:
pivot_index = randrange(len(collection))
pivot = collection.pop(pivot_index)

# Partition the remaining elements into two groups: lesser or equal, and greater
lesser = [item for item in collection if item <= pivot]
greater = [item for item in collection if item > pivot]
# Initialise empty lists to store the elements

lesser = [] # Stores elements less than or equal to the pivot
greater = [] # Stores elements greater than the pivot

# Loop through the collections and partition
for item in collection:
if item <= pivot:
lesser.append(item)
else:
greater.append(item)

# Recursively sort the lesser and greater groups, and combine with the pivot
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
Expand Down