Seyed Masoud Hosseini · Overview · Study log · Weekly summaries · Ideas · Search · Transcript · RSS feed
Design & Analysis of Algorithms · Lecture 8 of 34 · 1:21:52
6. Randomization: Matrix Multiply, Quicksort
Study guide
What this lecture covers
The lecture answers what it means for an algorithm to use randomness to make decisions, and how to analyze the resulting probabilistic guarantees on correctness and runtime. It introduces the distinction between Monte Carlo algorithms (probably correct, deterministically fast) and Las Vegas algorithms (always correct, probably fast), then works through two concrete examples: Freivalds' algorithm for verifying matrix multiplication, and several variants of quicksort.
This is the sixth lecture in MIT's Design and Analysis of Algorithms course, opening a new module on randomized algorithms. After watching, you should be able to state the difference between Monte Carlo and Las Vegas algorithms, explain how Freivalds' algorithm verifies A * B = C in O(n^2) time with bounded error probability, and describe why randomizing the pivot choice (or retrying until a balanced partition is found) gives quicksort expected O(n log n) running time.
Key ideas
- Randomized algorithm: an algorithm that generates random values during execution and makes decisions based on them, so that different runs on the same input can take different amounts of time or produce different outputs.
- Monte Carlo algorithms: probably correct — they run in a fixed time bound but may return an incorrect answer with some bounded probability, which can be driven down by running independent repetitions.
- Las Vegas algorithms: probably fast — they always return the correct answer but their running time is a random variable, so the goal is to bound the expected running time.
- Freivalds' algorithm: checks whether
C = A * Bforn x nmatrices inO(n^2)time by picking a random binary vectorrand testing whetherA(Br) = Cr, instead of recomputing the fullO(n^3)product. - No false negatives: if
AB = C, thenA(Br) = Cralways holds by associativity, so Freivalds' algorithm never rejects a correct product. - Bounded false positives: if
AB != C, the probability that a randomly chosenrfails to detect the error is at most one half, proved with a counting argument that pairs each "bad"r(whereDr = 0) with a "good" one (Dr' != 0) via a one-to-one mapping. - Basic quicksort: pivoting on a fixed position (such as the first element) gives
Theta(n^2)worst-case time, but on randomly shuffled input performs well in practice. - Median-based quicksort: using deterministic linear-time median finding as the pivot guarantees
Theta(n log n)worst-case time, but the constant factors make it impractical compared to basic quicksort. - Paranoid (Las Vegas) quicksort: repeatedly picks a random pivot and retries the partition until both sides have at most
3n/4elements, givingO(n log n)expected time with a simple recurrence-tree argument.
Walkthrough
Randomized algorithms, Monte Carlo and Las Vegas (0:00)
The lecture defines a randomized algorithm as one that generates random numbers and bases decisions on them, so repeated runs on the same input can differ in running time or output. It introduces Monte Carlo algorithms (probably correct, deterministically or reliably fast) and Las Vegas algorithms (always correct, probably fast), with primality testing mentioned as an example that can behave like a Monte Carlo algorithm.
Setting up Freivalds' algorithm (11:11)
The problem is verifying whether a claimed product C = A * B for n x n matrices is correct, without redoing the O(n^3) multiplication. Freivalds' algorithm picks a random binary vector r (each entry independently 1 with probability one half) and checks whether A(Br) = Cr, which requires three matrix-vector products, each O(n^2), for a total of O(n^2) per trial. Running k independent trials drives the false-positive probability down to 1/2^k while keeping the total cost O(kn^2).
Why there are no false negatives (27:23)
If AB = C, then A(Br) = (AB)r = Cr by associativity of matrix multiplication, so the algorithm always outputs "yes" when the product is actually correct.
Bounding the false-positive probability (29:26)
Defining the difference matrix D = AB - C, the claim to prove is that if D != 0, then a random r satisfies Dr != 0 with probability at least one half. The proof picks a nonzero entry D[i][j], constructs a one-hot vector v with a 1 in position j, and shows that for any "bad" r with Dr = 0, flipping the j-th bit of r (computing r' = r + v in mod-2 arithmetic) produces a "good" r' with Dr' != 0. Because this r <-> r' mapping is one-to-one, at least half of all possible r vectors are good, giving the claimed bound.
Basic quicksort and its worst case (49:51)
Quicksort is introduced as an in-place, divide-and-conquer sort where the work happens in the divide (partition) step rather than the merge step. Basic quicksort, which always pivots on a fixed element such as A[1], has Theta(n^2) worst-case time on sorted or reverse-sorted input, since the recurrence T(n) = T(n-1) + Theta(n) solves to quadratic time. In practice, shuffling the input first makes basic quicksort perform well, with expected Theta(n log n) time.
Guaranteeing worst-case time with median pivots (1:02:09)
Using the linear-time deterministic median-finding algorithm to select the pivot at every level guarantees perfectly balanced partitions, giving the recurrence T(n) = 2T(n/2) + Theta(n), which solves to Theta(n log n) worst-case time. The lecture notes this is impractical because the median-finding overhead makes it slower than basic quicksort in practice, illustrating the gap between asymptotic complexity and real performance.
Paranoid quicksort and its expected-time analysis (1:10:14)
Paranoid quicksort picks a random pivot, partitions, and retries until both resulting subarrays have size at most 3n/4 (a "good" pivot, which occurs with probability at least one half). This gives the recurrence T(n) = T(n/4) + T(3n/4) + 2cn, where the factor of 2 accounts for the expected number of retries. Drawing the (unbalanced) recursion tree shows that each level sums to 2cn of total work and the tree has at most log_{4/3}(n) levels, giving O(n log n) expected time.
Before you watch
- Review the earlier lecture on deterministic linear-time median finding (the five-way partition, median-of-medians algorithm), since it is reused here as an intelligent quicksort pivot strategy.
- Be comfortable with recurrence relations and recursion trees, since both Freivalds' probability bound and the paranoid quicksort analysis rely on careful counting arguments rather than the master method.
Check your understanding
- Why does Freivalds' algorithm never produce a false negative, but can produce a false positive?
- How does the one-to-one mapping between "bad" and "good" random vectors
restablish that at least half of allrvectors detect an incorrect matrix product? - Why does basic quicksort run in
Theta(n^2)worst-case time, and why does shuffling the input first fix this in practice? - Why is median-based quicksort worse in practice than basic quicksort, despite having a better worst-case asymptotic bound?
- In paranoid quicksort, why does the recurrence
T(n) = T(n/4) + T(3n/4) + 2cnstill solve toO(n log n)even though the partitions are unbalanced?
Vocabulary
- randomized algorithm (noun)
- An algorithm that uses random choices during its execution.
A randomized algorithm can behave differently each time it runs. - Monte Carlo algorithm (noun)
- An algorithm that runs quickly but might occasionally give a wrong answer.
A Monte Carlo algorithm trades some accuracy for guaranteed speed. - Las Vegas algorithm (noun)
- An algorithm that always gives the right answer but has unpredictable running time.
A Las Vegas algorithm is always correct, just sometimes slower. - false positive (noun)
- A result that incorrectly indicates something is true when it isn't.
Freivalds' algorithm can occasionally give a false positive. - false negative (noun)
- A result that incorrectly indicates something is false when it's actually true.
The algorithm never produces a false negative for a correct product. - associativity (noun)
- A mathematical property allowing grouped operations to be reordered without changing the result.
Associativity lets the algorithm rearrange the matrix multiplication. - probability (noun)
- A measure of how likely something is to happen.
The algorithm bounds the probability of a wrong answer. - one-to-one mapping (noun)
- A pairing where each item on one side matches exactly one item on the other side.
A one-to-one mapping proves at least half the vectors are good. - pivot (noun)
- An element used to split data into smaller and larger groups during sorting or searching.
Quicksort's speed depends heavily on choosing a good pivot. - in-place (adjective)
- Describing an algorithm that modifies data directly without needing much extra memory.
Quicksort is an in-place sorting algorithm. - expected time (noun)
- The average running time of an algorithm across all its random outcomes.
Paranoid quicksort has expected time of O(n log n). - retry (verb)
- To attempt an action again after an unsatisfactory result.
Paranoid quicksort will retry the partition if it's too unbalanced. - counting argument (noun)
- A proof technique that counts how many items satisfy a property to reach a conclusion.
A counting argument shows at least half the vectors are good. - constant factor (noun)
- A fixed multiplier hidden inside a running-time bound.
Median-based quicksort has large constant factors that slow it down. - primality testing (noun)
- Checking whether a number is a prime number.
Primality testing is mentioned as another Monte Carlo example. - trial (repetition) (noun)
- One single run of a randomized process.
Each trial of Freivalds' algorithm costs O(n^2) time. - shuffle (verb)
- To rearrange items into a random order.
Shuffling the input first makes basic quicksort perform well. - recursion tree (noun)
- A diagram showing how a recursive algorithm's calls branch out and how much work each level does.
Drawing the recursion tree shows the total work per level. - bound (probability) (verb)
- To limit how large or small a chance of something can be.
The proof bounds the false-positive probability by one half. - vector (binary) (noun)
- A list of numbers, here made only of 0s and 1s.
Freivalds' algorithm tests the product using a random binary vector. - in practice (phrase)
- In real, everyday use rather than in theory.
Basic quicksort performs well in practice despite its worst case. - independent (trials) (adjective)
- Not affected by or connected to any other outcome.
Running independent repetitions lowers the total error chance. - gap (theory vs. practice) (phrase)
- A noticeable difference between what theory predicts and what actually happens.
Median-based quicksort illustrates the gap between asymptotic and real performance. - worst-case (adjective)
- Describing the least favorable possible scenario for performance.
Basic quicksort has a bad worst-case running time on sorted input. - reject (verb)
- To refuse to accept something as correct.
The algorithm never rejects a genuinely correct product.
From the YouTube description
MIT 6.046J Design and Analysis of Algorithms, Spring 2015
View the complete course: http://ocw.mit.edu/6-046JS15
Instructor: Srinivas Devadas
In this lecture, Professor Devadas introduces randomized algorithms, looking at solving sorting problems with this new tool.
License: Creative Commons BY-NC-SA
More information at http://ocw.mit.edu/terms
More courses at http://ocw.mit.edu
← 5. Amortization: Amortized Analysis · R4. Randomized Select and Randomized Quicksort →
