From 34889fc6d8d3ac1cf5af11039cc1ec40185f778e Mon Sep 17 00:00:00 2001 From: BruceLee569 <49506152+BruceLee569@users.noreply.github.com> Date: Fri, 28 Jun 2019 23:55:31 +0800 Subject: [PATCH] Update quick_sort.py (#928) Use the last element as the first pivot, for it's easy to pop, this saves one element space. Iterating with the original list saves half the space, instead of generate a new shallow copy list by slice method. --- sorts/quick_sort.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 223c26fde..7e8c868eb 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -33,17 +33,16 @@ def quick_sort(collection): if length <= 1: return collection else: - pivot = collection[0] - # Modify the list comprehensions to reduce the number of judgments, the speed has increased by more than 50%. - greater = [] - lesser = [] - for element in collection[1:]: + # Use the last element as the first pivot + pivot = collection.pop() + # Put elements greater than pivot in greater list + # Put elements lesser than pivot in lesser list + greater, lesser = [], [] + for element in collection: if element > pivot: greater.append(element) else: lesser.append(element) - # greater = [element for element in collection[1:] if element > pivot] - # lesser = [element for element in collection[1:] if element <= pivot] return quick_sort(lesser) + [pivot] + quick_sort(greater)