October 2025
Intermediate to advanced
485 pages
13h 2m
English
As mentioned in Trade-Offs, the worst-case scenario for Quicksort is an array that’s already sorted. But there’s an easy way to fix this with a concept that is both ridiculously simple and yet counterintuitive at the same time: before executing Quicksort, you can first shuffle the array.
To shuffle an array means to put its values in random order, similar to shuffling a deck of cards. In Python, you can shuffle an array using the built-in random module:
| | import random |
| | |
| | array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| | random.shuffle(array) |
This modifies array by randomizing the order of its values.
I mentioned that this technique is both simple and counterintuitive at the same time. It’s simple because it attacks the problem ...
Read now
Unlock full access