snippetpythonMinor
Is this a proper quicksort algorithm in Python?
Viewed 0 times
thisquicksortalgorithmpythonproper
Problem
import random
def qsort(qslist):
small = []
big = []
if (len(qslist) 1):
pivot = qslist[int(random.randrange(len(qslist)))]
for x in range(len(qslist)):
if qslist[x] <= pivot:
small.append(qslist[x])
else:
big.append(qslist[x])
if(len(big) == 0):
big.append(pivot)
small.remove(pivot)
return qsort(small) + qsort(big)
qslist = [9,1,8,2,7,3,6,4,5]
print(qsort(qslist))Please give me advice while picking up Python. I'm trying to do so while at the same time doing some basic algorithms.
- Have I understood how the quicksort algorithm work?
- Please give me some general feedback on the Python code.
Solution
Some comments:
The code in the original questions with the suggested improvements would be as follows:
Edit: If you prefer to avoid traversing the array three times, a partition
function to do that very similar to the one in the original question would be:
- Write docstrings to document code
- Use
if/elseinstead ofif/elifif possible
- Use list comprehensions
- Use
random.choiceto get a random element from a non-empty sequence
The code in the original questions with the suggested improvements would be as follows:
import random
def qsort(qslist):
""""Quicksort implementation."""
if len(qslist) pivot]
return qsort(small) + equal + qsort(big)
qslist = [9,1,8,2,7,3,6,4,5]
print(qsort(qslist))Edit: If you prefer to avoid traversing the array three times, a partition
function to do that very similar to the one in the original question would be:
def partition(qslist):
"""Partition array using a pivot value."""
small = []
equal = []
big = []
pivot = random.choice(qslist)
for x in qslist:
if x < pivot:
small.append(x)
elif x == pivot:
equal.append(x)
else:
big.append(x)
return small, equal, bigCode Snippets
import random
def qsort(qslist):
""""Quicksort implementation."""
if len(qslist) < 2:
return qslist
pivot = random.choice(qslist)
small = [x for x in qslist if x < pivot]
equal = [x for x in qslist if x == pivot]
big = [x for x in qslist if x > pivot]
return qsort(small) + equal + qsort(big)
qslist = [9,1,8,2,7,3,6,4,5]
print(qsort(qslist))def partition(qslist):
"""Partition array using a pivot value."""
small = []
equal = []
big = []
pivot = random.choice(qslist)
for x in qslist:
if x < pivot:
small.append(x)
elif x == pivot:
equal.append(x)
else:
big.append(x)
return small, equal, bigContext
StackExchange Code Review Q#59229, answer score: 2
Revisions (0)
No revisions yet.