You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/lectures/misc/sorting.md
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -204,13 +204,13 @@ At a high level, the algorithm
204
204
205
205
- pick a "median" value (the pivot), at the middle of the list to be sorted,
206
206
- 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,
208
208
- 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.
209
209
210
210
In detail, this algorithm works as follows:
211
211
212
212
- 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:
214
214
215
215
- It first look for the smallest `left` index such that `listP[left] > pivot`,
216
216
- 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
233
233
- Then, sorting each sub-list takes $T(n / 2)$.
234
234
- So, we get that $T(n) = O(n) + 2 \times T(n / 2)$,
235
235
- 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))$.
237
237
238
238
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