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.
This commit is contained in:
BruceLee569 2019-06-28 23:55:31 +08:00 committed by John Law
parent be4150c720
commit 34889fc6d8

View File

@ -33,17 +33,16 @@ def quick_sort(collection):
if length <= 1: if length <= 1:
return collection return collection
else: else:
pivot = collection[0] # Use the last element as the first pivot
# Modify the list comprehensions to reduce the number of judgments, the speed has increased by more than 50%. pivot = collection.pop()
greater = [] # Put elements greater than pivot in greater list
lesser = [] # Put elements lesser than pivot in lesser list
for element in collection[1:]: greater, lesser = [], []
for element in collection:
if element > pivot: if element > pivot:
greater.append(element) greater.append(element)
else: else:
lesser.append(element) 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) return quick_sort(lesser) + [pivot] + quick_sort(greater)