Skip to content

refactor: pivot is randomly chosen #6643

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

Merged
merged 1 commit into from
Oct 5, 2022
Merged
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
12 changes: 10 additions & 2 deletions sorts/quick_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"""
from __future__ import annotations

from random import randrange


def quick_sort(collection: list) -> list:
"""A pure Python implementation of quick sort algorithm
Expand All @@ -26,11 +28,17 @@ def quick_sort(collection: list) -> list:
"""
if len(collection) < 2:
return collection
pivot = collection.pop() # Use the last element as the first pivot
pivot_index = randrange(len(collection)) # Use random element as pivot
pivot = collection[pivot_index]
greater: list[int] = [] # All elements greater than pivot
lesser: list[int] = [] # All elements less than or equal to pivot
for element in collection:

for element in collection[:pivot_index]:
(greater if element > pivot else lesser).append(element)

for element in collection[pivot_index + 1 :]:
(greater if element > pivot else lesser).append(element)

return quick_sort(lesser) + [pivot] + quick_sort(greater)


Expand Down