QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many versions of QuickSort that pick pivot(s) in different ways. Here I’m going to show 4 ways of implementing QuickSort in Python.
Version 1
Version 1 is the most common way to implement QuickSort. Here we pick the first element as the pivot.
1 | def qs1(t, lo, hi): |
Version 2
Version 2 is from MIT’s Introduction to Algorithms (CLRS).
1 | def qs2(array, l, r): |
Version 3
Version 3 is a simplified way of implementing QuickSort. The pivot is the last element of the list.
1 | def qs3(t): |
Version 4
Version 4 is the improved quicksort (from Prof. Siegel’s textbook). Note that less comparisons are made.
1 | def qs4(t, lo, hi): |
Comparison
Among all the three, Version 3 is the fastest when the data isn’t very large (less than 1 million). It also comes with a cost of space, since multiple lists are created. However, when the data is larger than 1 million, Version 4 becomes the fastest. To time the performance, we could use Python’s built-in module time
. For instance, to time Version 3’s performance:
1 | import time |
To generate random numbers for testing, we use Python’s random
module. For example,
1 | import random |