Skip to content

Commit

Permalink
Update quick_sort.py (TheAlgorithms#928)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
BruceLee569 authored and poyea committed Jun 28, 2019
1 parent be4150c commit 34889fc
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions sorts/quick_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down

0 comments on commit 34889fc

Please sign in to comment.