From 8cce0d463a0f65c22769fe4f0750acbeed2e0d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9rome=20Eertmans?= Date: Wed, 5 Oct 2022 12:32:07 +0200 Subject: [PATCH] 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 --- 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 b099c7886..70cd19d7a 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -9,6 +9,8 @@ python3 quick_sort.py """ 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)