Follow these steps to implement:
- Choose any element of the list to be the pivot.
- Divide all other elements (except the pivot) into two partitions.
- All elements less than the pivot must be in the first partition (lower half list).
- All elements greater than the pivot must be in the second partition (upper half list).
- Use recursion to sort both partitions.
- Join the first sorted partition, the pivot, and the second sorted partition
def qsort(list):
if not list:
return []
else:
pivot = list[0]
less = [x for x in list if x < pivot]
more = [x for x in list[1:] if x >= pivot]
return qsort(less) + [pivot] + qsort(more)
Example:
someList = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3]
print qsort(
someList )
[1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9]
Enjoy the sort.