Python Program for Quick Sort
Intermediate · Searching and sorting
Quick sort picks one element, called the pivot, and splits the rest of the list into the elements smaller than the pivot and the elements larger than it. The pivot is then in its final place, and the two sides are sorted the same way. This program uses the last element as the pivot and prints each split.
Program
Original list: [33, 10, 55, 71, 29, 3, 18, 42]
Pivot 42: [33, 10, 29, 3, 18] | 42 | [55, 71]
Pivot 18: [10, 3] | 18 | [33, 29]
Pivot 3: [] | 3 | [10]
Pivot 29: [] | 29 | [33]
Pivot 71: [55] | 71 | []
Sorted list: [3, 10, 18, 29, 33, 42, 55, 71]How it works
- The last element, 42, is the first pivot.
- Every other element goes into
smallerorlargerdepending on how it compares with the pivot. - Everything in
smallerbelongs before the pivot and everything inlargerafter it, so the pivot is already where it belongs in the sorted list. - The function then sorts
smallerandlargerby calling itself, and joins the pieces: smaller, pivot, larger. - Quick sort usually takes about n x log n steps, but a list that is already sorted gives bad pivots and about n x n steps.
Other ways to write it
In place, with a partition function
Sorted in place: [3, 10, 18, 29, 33, 42, 55, 71]
This is the textbook version: partition() moves the smaller items to the left by swapping inside the same list, so no new lists are made.
Short version with list comprehensions
Sorted list: [3, 10, 18, 29, 33, 42, 55, 71]
The same idea in a few lines, using the first item as the pivot. It is easy to read, but it builds many new lists.
Try it yourself
Run the main program on [1, 2, 3, 4, 5, 6] and count how many lines it prints, to see why a sorted list is the worst case for this pivot choice.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises