October 2025
Intermediate to advanced
485 pages
13h 2m
English
In the previous chapter, it appeared that possibly the most significant advantage of Mergesort over Quicksort is that Mergesort runs at O(N log N) in all scenarios, while Quicksort is O(N2) in the worst case. Again, for Quicksort, the worst case is an array that’s already sorted.
It would be nice to see how this plays out in actual time, so let’s benchmark it. Here’s our code for benchmarking Quicksort on a sorted array of size 10,000:
| | import timeit |
| | setup_code = ''' |
| | import quicksort |
| | |
| | array = [] |
| | for i in range(10000): |
| | array.insert(0, i) |
| | sortable_array = quicksort.SortableArray(array) |
| | ''' |
| | |
| | test_code = ''' |
| | sortable_array.quicksort(0, len(array) - 1) |
| | ''' |
| | |
| | print(timeit.repeat(stmt=test_code, ... |
Read now
Unlock full access