Overview
This class began with a clarification of lab/assignment evaluation, then recapped binary search, merge sort and quick sort before going deeper into quick sort: pivot selection, worst-case behaviour, recurrence relations, the median-of-3 pivot strategy, and a quick-sort + insertion-sort hybrid ("quick insertion"). It then explained why quick sort is faster than merge sort in practice, and introduced the maximum subarray problem (motivated by a stock buy/sell story) together with its brute-force solution. The class previewed the three solution variants of maximum subarray (brute force, divide and conquer, dynamic programming) and closed early due to the instructor's exam duty, with divide and conquer announced for the next class.
Learning outcomes
- Explain the lab/assignment evaluation scheme (lab assignments vs. separate quiz).
- State the best/average/worst-case complexities of binary search, merge sort and quick sort, and the conditions under which each worst case arises.
- Describe quick sort's partitioning mechanism and the pivot selection options (first, last, median, random).
- Apply the median-of-3 pivot strategy and explain why it avoids the worst case.
- Describe the quick insertion hybrid and set its recursion base case to a small threshold (e.g., size ≤ 5).
- Justify why quick sort is faster than merge sort in practice despite merge sort's better worst case.
- Formulate and solve the best-case and worst-case recurrences for quick sort.
- Reformulate the stock buy/sell problem as the maximum subarray problem and handle all-positive and all-negative arrays.
- Compute the maximum subarray by brute force in order n².
- Explain why the divide-and-conquer maximum subarray must consider the crossing subarray, not just the left and right halves.
Core concepts
Lab/assignment evaluation
There are four lab assignments; lab work is for practice, and a separate quiz will be conducted. Lab assessment marks may be shown/added if beneficial — if you do well in the quiz, those marks are not added; if you do not do well, the lab assessment marks are added. This matters because it defines how the course is graded and how lab effort converts into marks.
Recap: binary search, merge sort, quick sort
Merge sort recursively divides a large problem, requires additional space for storing results, and is n log n for best, worst and average cases. Binary search recursively divides and compares with the middle element, is order log n, and requires the array to always be sorted. Quick sort's best/average case complexity is equivalent to merge sort; its worst case reaches n² when the pivot is selected as the extreme element (smallest or largest) in each iteration. These recaps set the baseline against which quick sort's behaviour is analysed.
Quick sort mechanism
Identify a pivot and fix its position; elements greater than the pivot go to one side, less than to the other. The scan starts from the left (left = left + 1), goes left to right; if the condition fails, it changes direction toward the left. This continues until left index ≤ right index; if that condition fails, the algorithm terminates. This mechanism is the basis for all the complexity analysis that follows.
Pivot selection options
Pivot options are: first element, last element, median element, random selection. All of these may lead to the worst case (not guaranteed 100%, but may). This is why a smarter pivot strategy (median of 3) is needed.
Median of 3
A strategy for pivot selection in quick sort that avoids the worst case, reducing computational time requirement by "14 plus" (as stated). Basic idea: take three indexes — low (first index), median index, high (last index) — and arrange them so that first < median < last. Then replace the median with the second-last element, and that acts as the pivot; then run the quick sort operation. It connects to pivot selection: it is the practical fix for the worst case discussed earlier.
Quick insertion (quick sort + insertion sort hybrid)
For very small arrays, quick sort does not perform as well as insertion sort (no visible reduction in clock time; only a few milliseconds difference), because quick sort still divides, selects a pivot, etc. Variant: when using quick sort recursively, switch to insertion sort for small arrays. The base case (stopping criterion of recursion) is changed: instead of stopping at size ≤ 1, stop when array size ≤ 5 (any threshold can be set) and directly apply insertion sort. Example visualization: array of size 20 → partition into 8 and 12 → further partitions produce sizes like 5, 3, 7; wherever size ≤ 5, immediately call insertion sort; the 7 is further divided into 3 and 4, and insertion sort is called there too. Why this is still better despite insertion sort being n²: we are dealing with only about one-fourth of the size (n/4), so n² is not very big relative to the maximum number of elements; clock time difference is small. Also, when subarrays are fairly sorted, insertion sort tends toward its best case.
Why quick sort is faster than merge sort
Due to external memory requirement (caching requirement) — merge sort needs extra space, quick sort does not. The inner loop consists of an increment or decrement by one, a test, and a jump — this is faster. In merge sort, comparisons involve the entire array and then sorting in order; in quick sort, comparisons are confined around a single element's placement (fixing the pivot's position), with no extra juggling as in merge sort. In the Q&A: the worst case will rarely appear; we are not comparing on the worst case. If we do a worst-case comparison, merge sort is better than quick sort — but we are not assuming someone will provide an already sorted array for sorting.
Maximum subarray problem
Motivating story: a share-market-listed company (Volatile Chemical Corporation) whose shares are volatile. Condition: buy one unit of stock only one time and sell it on a later date (not the same day; selling after the closing of the trading day is allowed; intraday stock prices are not applicable here). You are allowed to know future stock prices, but no ML technique is to be applied. Objective: buy at the lowest price and sell at the highest possible price — identify entry and exit dates. With n days, we are trying to do nC2 (choose two days). Reformulated: given an array containing both positive and negative numbers, identify a subarray whose sum is highest — the maximum subarray (maximum sum subarray). If all elements are positive: the maximum subarray is the sum of all elements. If all elements are negative: choose the least number with negative sign (the negative value closest to zero, e.g., between −1 and −20 choose −1), because adding negatives increases negativity. This problem is the bridge to the next topic: it has three solution forms with complexities n², n log n and n.
Brute force for maximum subarray
Form all combinations and pick whichever gives the highest sum. Implementation: one loop for row and one loop for column → complexity order n². Drawback: irrespective of the available solution, all possibilities are explored. This is the first of the three variants previewed.
Divide and conquer for maximum subarray (crossing case)
A divide-and-conquer solution that considers only the best subarray wholly in the left half and wholly in the right half is not correct — it must also consider the crossing subarray, one that starts in the left half and ends in the right half. That omission is the classic wrong solution. The key structural fact that makes the crossing case solvable in linear time is that the crossing subarray is the best suffix of the left half joined to the best prefix of the right half, so each side is found by a single linear scan outward from the midpoint. This is the second of the three variants previewed.
Three variants of maximum subarray (preview)
Brute force: order n². Divide and conquer: order n log n (as stated in the lecture). Dynamic programming: order n — the best approach; drawback is that it requires memory to store previous outcomes. This preview frames the upcoming classes.
Cadence algorithm (flagged)
Named by the instructor as the well-known algorithm "in this" (dynamic programming); students are told to check it out. No further detail given. The name is as spoken in the transcript and the intended algorithm name is not certain — verify against the lecture material.
Formulas and maths
- Quick sort best-case recurrence: $T(n) = 2T(n/2) + O(n)$ — $T(n)$ is the time for size $n$, split into two halves of size $n/2$ plus linear work; used when the pivot splits the problem into equal halves (e.g., problem size 10 → 5 and 5).
- Quick sort worst-case recurrence: $T(n) = T(n-1) + O(n)$ — one subproblem of size $n-1$ plus linear work; used when the pivot is the extreme element at every step.
- Worst-case expansion: $T(n) = T(n-1) + 1$, then $T(n-2) + 1 + 2$, then $T(n-3) + \dots$ — shows the recurrence unrolling to the extreme case.
- Worst-case structure: $T(n) = T(n-i) + i - 1 + c \cdot n$ — $i$ is the number of elements peeled off, $c \cdot n$ the linear partitioning cost; this is how the worst case reaches order $n^2$.
- Analysis components: pivot selection is $O(1)$ ($O(3)$ comparisons for median of 3, effectively $O(1)$); partitioning is linear time, $O(n)$ (maximum of $n$ comparisons); recursive division contributes $\log n$ in the best case.
- Best case: $O(1) + O(n) + \log n \rightarrow n \log n$ — used to derive quick sort's best-case complexity.
- Worst case: pivot selection $O(1)$, partitioning $O(n)$, recursive call again $O(n) \rightarrow n^2$ — used because the recursive call is made for all $n$ entries when the pivot chosen is extremely small at each step.
- Brute force maximum subarray: two nested loops → $O(n^2)$ — used as the baseline solution.
- Number of subarrays checked by brute force: $n(n+1)/2$ — the count of contiguous subarrays of an array of $n$ elements, which is why the brute force is order $n^2$.
- Divide-and-conquer maximum subarray: $T(n) = 2T(n/2) + O(n)$ — left half, right half, and a linear crossing scan → $n \log n$.
- Maximum subarray complexities: brute force $n^2$, divide and conquer $n \log n$, dynamic programming $n$ — used to compare the three variants.
Worked examples
Stock price example (dates/prices as spoken): - Prices mentioned: 100, then 113, then 110; the least price the share could go was 63; on some date it goes to 9401 (as spoken). - If you buy on the 7th and sell on the 11th, you get the highest profit margin. - Array fragment given: 13, −3, −25, 20, −3, 20, … (dot dot dot, so on). - Profit progression example: profit is zero initially; next day profit is 13; then 13 − 3 = 10? [unclear — transcript reads "13 minus 3 minus 25 20 minus 3 16 minus 23 18 and so on"]; the target is to identify the highest possible value / maximum sum.
Brute force maximum subarray example (7 elements, indices 1–7): - Step 1: start with the first element; running sums: −4, then −5, then −2, then −3, then −1, then −3; highest among these is 2. - Step 2: start with the second index (−6): −7, −4, −5, −3, −5; maximum is −3. - Step 3: start with the third index (−1): 2, 1, 3, then −1; maximum is 3. - Step 4: start with the fourth index (3): 2, 4, 2; maximum is 4. - Step 5: start with the fifth index (−1): −1, 1, −1; maximum is 4 [as spoken]. - Step 6: start with the sixth index (2): 0; maximum is 2. - Step 7: last index: −2; maximum is −2. - Overall highest is 4, obtained by adding 3, 1, and 2 — i.e., the maximum subarray is index 4 to index 6. - For 7 elements the brute force checks $7 \cdot 8 / 2 = 28$ subarrays, matching the $n(n+1)/2$ count.
Student's example (from Q&A): array with 20 as the highest positive number; if you add surrounding negatives they become more negative, so choose 21 [as spoken]; e.g., 20, −11, 25 — enter on this day and exit on that day for maximum profit; the lower negative number can be on either side, with negative numbers in between.
Questions asked in class
Q (assignment): Will there be a separate assignment besides labs 1–4, or only the lab assignments count? A: There will be a separate quiz; lab work is practice. If marks are demanded, the lab assessment can be shown so they can be added. If you do well in the quiz, the lab marks are not added; if you do not do well, the lab marks are added.
Q: If quick sort takes n² in the worst case and merge sort takes n log n, how can we say quick sort is faster? A: The worst case will rarely appear; we are not comparing on the worst case. In a worst-case comparison, merge sort is better — but we are not assuming someone will provide an already sorted array for sorting.
Q: What about non-numeric data (e.g., strings)? Can we convert to ASCII and then sort to increase performance? A: Here we are primarily talking about numbers. For alphabetical data, you convert into ASCII code — A, B, C, D have different numbers (around 60s; for smaller letters around 90s, as spoken) — and sort accordingly; 'a' has a lower number and 'z' a higher number. The scheme is applicable; just convert to its equivalent (e.g., binary equivalent) and perform the sorting.
Q (on the array with negative values on both sides): Which median side is taken? A: It is not about the median; we select the subarray that gives the highest values. In the example, the only possibility is to enter before 13 and exit after 13; or take 20 (the highest positive number) — adding other elements makes it more negative. E.g., 20, −11, 25: enter on this day and exit on that day for maximum profit; the lower negative number can be on either side, with negative numbers in between.
Q: For maximum subarray, are we using quick sort? A: No — before maximum subarray we will do a separate algorithm; it is not a quick sort variant. On how to identify which algorithm/solution to apply: for sorting, use insertion/merge/quick depending on the number of elements and how the elements are (fairly sorted or not, size 10/20/30 → insertion; very large → quick sort and merge sort; if memory is constant → definitely quick sort).
Q: Is "balance sub array" the same kind of question as maximum subarray, with the same solution? A: [Unclear] — probably a different concept; balance of error is not getting the maximum sum. The instructor will check and discuss separately if needed. Maximum subarray is interesting because it has three solution forms — brute force, divide and conquer, and the dynamic programming variant — with complexity varying from n² to n log n to n.
Q: Can we use dual pivot in quick sort? A: Dual, triple, or four/five pivots are applicable in the parallel variant. There is a subject called parallel analysis of algorithms where subproblems are treated separately on different processors, requiring multiple pivots. In sequential execution, choosing multiple pivots at multiple places executes sequentially and is not much beneficial. There is a parallel variant of quick sort; multiple pivot selection is allowed there. Predefined sort methods use dual pivot in quick sort in Java and other languages — maybe they do some sort of parallelism, but we are not aware of it.
Q (divide-and-conquer maximum subarray): Is it correct to consider only the best subarray wholly in the left half and wholly in the right half? A: False — the crossing subarray must also be considered. Leaving it out is the classic wrong solution; the crossing case is what makes the divide-and-conquer version correct.
Key takeaways
- Quick sort's worst case is $n^2$ when the pivot is the extreme element (smallest or largest) in each iteration; best/average case is $n \log n$, equivalent to merge sort.
- Pivot options — first, last, median, random — may all lead to the worst case (not guaranteed 100%, but may).
- Median of 3 arranges low < median < high, replaces the median with the second-last element, and uses that as the pivot; it avoids the worst case and reduces computational time requirement by "14 plus" (as stated).
- Quick insertion changes the recursion base case: stop at size ≤ 5 (any threshold can be set) and apply insertion sort directly.
- Quick insertion is still better despite insertion sort being $n^2$ because only about one-fourth of the size ($n/4$) is handled, and fairly sorted subarrays push insertion sort toward its best case.
- Quick sort beats merge sort in practice due to no external memory (caching) requirement, a faster inner loop (increment/decrement, test, jump), and comparisons confined around the pivot's placement.
- In a worst-case comparison merge sort is better than quick sort, but the worst case rarely appears and we do not assume an already sorted input.
- Maximum subarray: with all positive elements the answer is the sum of all elements; with all negative elements choose the negative closest to zero (e.g., between −1 and −20 choose −1).
- Brute force maximum subarray forms all combinations with two nested loops → $O(n^2)$, checks $n(n+1)/2$ subarrays, and explores all possibilities regardless of the available solution.
- Divide-and-conquer maximum subarray must consider the crossing subarray as well as the left-half and right-half bests; the crossing case is solvable in linear time, giving $T(n) = 2T(n/2) + O(n) \rightarrow n \log n$.
- The three maximum subarray variants have complexities $n^2$ (brute force), $n \log n$ (divide and conquer) and $n$ (dynamic programming, which needs memory to store previous outcomes).
- Algorithm choice for sorting: size 10/20/30 or fairly sorted → insertion; very large → quick sort and merge sort; constant memory → definitely quick sort.
- Multiple pivots (dual, triple, four/five) are beneficial only in the parallel variant; in sequential execution they are not much beneficial.
Exam-style questions
Q1. Derive the best-case and worst-case recurrences for quick sort and state the resulting complexities. Outline: Best case $T(n) = 2T(n/2) + O(n)$ (equal split, e.g., 10 → 5 and 5) → $n \log n$. Worst case $T(n) = T(n-1) + O(n)$ (extreme pivot each time), expanded as $T(n-1)+1$, $T(n-2)+1+2$, $T(n-3)+\dots$, and structured as $T(n) = T(n-i) + i - 1 + c \cdot n$ → $n^2$. Components: pivot selection $O(1)$, partitioning $O(n)$, recursion $\log n$ in the best case.
Q2. Explain the median-of-3 pivot strategy and why it helps. Outline: Take low (first), median index, high (last); arrange so first < median < last; replace the median with the second-last element and use it as the pivot; then run quick sort. It avoids the worst case, reducing computational time requirement by "14 plus" (as stated).
Q3. What is quick insertion and why is it faster for small arrays despite insertion sort being $n^2$? Outline: Change the recursion base case from size ≤ 1 to size ≤ 5 (any threshold) and call insertion sort directly; e.g.,
Q4. Why is it wrong to solve maximum subarray by divide and conquer using only the best left-half and best right-half subarrays? Outline: That omits the crossing subarray, which starts in the left half and ends in the right half — the classic wrong solution. The correct version also computes the crossing case, which is linear because it is the best suffix of the left half joined to the best prefix of the right half. Recurrence $T(n) = 2T(n/2) + O(n) \rightarrow n \log n$.
Q5. How many subarrays does the brute-force maximum subarray examine, and what is the resulting complexity? Outline: $n(n+1)/2$ contiguous subarrays (e.g., 28 for $n = 7$), found with two nested loops → $O(n^2)$.
Glossary
- Maximum subarray: the contiguous subarray of an array (with positive and negative entries) whose sum is largest.
- Crossing subarray: a subarray that starts in the left half and ends in the right half of the array; the case a divide-and-conquer maximum subarray must add to the left-half and right-half bests.
- Median of 3: pivot strategy taking low, median index and high, arranging first < median < last, and using the second-last element as pivot.
- Quick insertion: quick sort hybrid that switches to insertion sort once subarrays reach a small threshold (e.g., size ≤ 5).