Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit34889fc

Browse files
BruceLee569poyea
authored andcommitted
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.
1 parentbe4150c commit34889fc

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

‎sorts/quick_sort.py‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,16 @@ def quick_sort(collection):
3333
iflength<=1:
3434
returncollection
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-
forelementincollection[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+
forelementincollection:
4142
ifelement>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
returnquick_sort(lesser)+ [pivot]+quick_sort(greater)
4847

4948

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp