Skip to content

Commit 68e6ecd

Browse files
ClémentClément
authored andcommitted
Notes on quicksort.
1 parent 78eee61 commit 68e6ecd

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

source/lectures/misc/sorting.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -204,13 +204,13 @@ At a high level, the algorithm
204204

205205
- pick a "median" value (the pivot), at the middle of the list to be sorted,
206206
- organize the list so that the values to the left of the pivot are smaller than the pivot, and the values greater than or equal to the pivot are to its right,
207-
- then recursively call quicksort on the values to the left of the pivot, and on the values to the right of the pivot,
207+
- then recursively call quicksort on the list on the left of the pivot, and on the list on the right of the pivot,
208208
- when the lists left to be sorted are of size 1, we know that quicksort is done (a list of size 1 is sorted!), the list is sorted.
209209

210210
In detail, this algorithm works as follows:
211211

212212
- Choose a pivot: we use the `medianOfThree` method to select an element from the list as the pivot. Other ways of choosing the pivot exist, this "median-of-three" technique is optimal when no information about the ordering of the input is known. Note that this method actually sorts those three elements (at the beginning, center and end of the list to be sorted), and take the median one as the `pivot`,
213-
- The `while (left <= right)` loop in `QuickSort` proceeds as follows:
213+
- Partition the list: the `while (left <= right)` loop in `QuickSort` proceeds as follows:
214214

215215
- It first look for the smallest `left` index such that `listP[left] > pivot`,
216216
- It then look for the greatest `right` index such that `pivot <= listP[right]` and `left <= right`,
@@ -233,6 +233,6 @@ The **best case** is when the pivot always divides the array in two equal halves
233233
- Then, sorting each sub-list takes $T(n / 2)$.
234234
- So, we get that $T(n) = O(n) + 2 \times T(n / 2)$,
235235
- Iterating this mechanism, we get that $T(n) = 2^k \times T(n/(2^k)) + k \times n$, for $n = 2^k$,
236-
- Then, we get $k = log2(n)$ and $T(n) = n \times T(1) + n \times \log(n) = O(n \times \log(n))$.
236+
- Then, we get $k = \log(n)$ and $T(n) = n \times T(1) + n \times \log(n) = O(n \times \log(n))$.
237237

238238
The **average case** is also $O(n \times \log(n))$, but if we are unlucky with our pivot (which is always at the beginning or at the end of the list), then we have to keep on sorting a sub-list that is linear $n$ (we partition our list in lists of size $n-1$ and $1$), and we get a **worst case** complexity of $O(n^2)$.

0 commit comments

Comments
 (0)