ADVANCED ALGORITHMS - ADVANCED TECHNIQUES:Randomized Algorithms
Mastering randomized algorithms concepts and implementation.
Randomized Algorithms
Types
Las Vegas
Always correct, running time is random.
Monte Carlo
Running time fixed, correctness is random.
Quickselect (Randomized)
import random
def quickselect(arr, k):
"""Find k-th smallest element"""
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
left = [x for x in arr if x < pivot]
right = [x for x in arr if x > pivot]
equal = [x for x in arr if x == pivot]
if k < len(left):
return quickselect(left, k)
elif k < len(left) + len(equal):
return pivot
else:
return quickselect(right, k - len(left) - len(equal))
Randomized Quicksort
def quicksort_randomized(arr):
"""Randomized quicksort"""
if len(arr) <= 1:
return arr
pivot = random.choice(arr)
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort_randomized(left) + middle + quicksort_randomized(right)
Min-Cut (Karger's Algorithm)
def karger_min_cut(graph):
"""Karger's randomized min-cut algorithm"""
# Contract edges randomly
# Repeat to get min-cut with high probability
pass
Practice Problems
- Randomized quicksort
- Quickselect
- Randomized min-cut
- Probabilistic analysis
Progress