Skip to content

Commit 8cce0d4

Browse files
authored
refactor: pivot is randomly chosen (#6643)
As described in #6095, this reduces the chances to observe a O(n^2) complexity. Here, `collection.pop(pivot_index)` is avoided for performance reasons. Fixes: #6095
1 parent 087a3a8 commit 8cce0d4

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

Diff for: sorts/quick_sort.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
"""
1010
from __future__ import annotations
1111

12+
from random import randrange
13+
1214

1315
def quick_sort(collection: list) -> list:
1416
"""A pure Python implementation of quick sort algorithm
@@ -26,11 +28,17 @@ def quick_sort(collection: list) -> list:
2628
"""
2729
if len(collection) < 2:
2830
return collection
29-
pivot = collection.pop() # Use the last element as the first pivot
31+
pivot_index = randrange(len(collection)) # Use random element as pivot
32+
pivot = collection[pivot_index]
3033
greater: list[int] = [] # All elements greater than pivot
3134
lesser: list[int] = [] # All elements less than or equal to pivot
32-
for element in collection:
35+
36+
for element in collection[:pivot_index]:
3337
(greater if element > pivot else lesser).append(element)
38+
39+
for element in collection[pivot_index + 1 :]:
40+
(greater if element > pivot else lesser).append(element)
41+
3442
return quick_sort(lesser) + [pivot] + quick_sort(greater)
3543

3644

0 commit comments

Comments
 (0)