Skip to content

Commit 34889fc

Browse files
BruceLee569poyea
authored andcommitted
Update quick_sort.py (TheAlgorithms#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.
1 parent be4150c commit 34889fc

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

sorts/quick_sort.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,16 @@ def quick_sort(collection):
3333
if length <= 1:
3434
return collection
3535
else:
36-
pivot = collection[0]
37-
# Modify the list comprehensions to reduce the number of judgments, the speed has increased by more than 50%.
38-
greater = []
39-
lesser = []
40-
for element in collection[1:]:
36+
# Use the last element as the first pivot
37+
pivot = collection.pop()
38+
# Put elements greater than pivot in greater list
39+
# Put elements lesser than pivot in lesser list
40+
greater, lesser = [], []
41+
for element in collection:
4142
if element > pivot:
4243
greater.append(element)
4344
else:
4445
lesser.append(element)
45-
# greater = [element for element in collection[1:] if element > pivot]
46-
# lesser = [element for element in collection[1:] if element <= pivot]
4746
return quick_sort(lesser) + [pivot] + quick_sort(greater)
4847

4948

0 commit comments

Comments
 (0)