From 12eb528e489c7058cf50d7373ac2a717167ce561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9rome=20Eertmans?= Date: Tue, 4 Oct 2022 11:07:47 +0200 Subject: [PATCH] refactor: pivot is randomly chosen 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 --- sorts/quick_sort.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index b099c78861ba..70cd19d7afe0 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -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 @@ -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)