The world behaves randomly – randomly generated input solved by traditional algorithm
Average-case Analysis
The algorithm behaves randomly – make random decisions as the algorithm processes the worst-case input
Randomized Algorithms
Why Randomize
Efficient deterministic(确定性) algorithms that always yield the correct answer are a special case of –
efficient randomized algorithms that only need to yield the correct answer with high probability
randomized algorithms that are always correct, and run efficiently in expectation
A Quick Review
Pr[A] := the probability of the even A
A := the complementary of the even A (A did not occur )
Pr[A]+Pr[A]=1
E[X] := the expectation (the “average value”) of the random variable X
E[X]=j=0∑∞j⋅Pr[X=j]
Hiring Problem
Hire an office assistant from headhunter
Interview a different applicant per day for N days
Interviewing Cost = Ci << Hiring Cost = Ch
Analyze interview & hiring cost instead of running time
Assume M people are hired
Minimize the total cost: O(NCi+MCh)
Naive Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int Hiring ( EventType C[ ], int N ) { /* candidate 0 is a least-qualified dummy candidate */ int Best = 0; int BestQ = the quality of candidate 0; for (i = 1; i <= N; i++) { Qi = interview( i ); /* Ci */ if ( Qi > BestQ ) { BestQ = Qi; Best = i; hire( i ); /* Ch */ } } return Best; }
Worst case: The candidates come in increasing quality order
T(N)=O(NCh)
Randomized Algorithm
Assume candidates arrive in random order
X = number of hires
E[X]=j=1∑Nj⋅Pr[X=j]Xi={1,0,if candidate i is hiredif candidate i is NOT hiredX=i=1∑NXiE[Xi]=Pr[candidate i is hired]=1/iE[X]=E[i=1∑NXi]=i=1∑NE[Xi]=i=1∑N1/i=lnN+O(1)O(ChlnN+NCi)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int RandomizedHiring ( EventType C[ ], int N ) { /* candidate 0 is a least-qualified dummy candidate */ int Best = 0; int BestQ = the quality of candidate 0;
randomly permute the list of candidates;
for ( i=1; i<=N; i++ ) { Qi = interview( i ); /* Ci */ if ( Qi > BestQ ) { BestQ = Qi; Best = i; hire( i ); /* Ch */ } } }
Randomized Permutation Algorithm
Target: Permute array A[ ]
Assign each element A[ i ] a random priority P[ i ], and sort
1 2 3 4 5 6 7
void PermuteBySorting ( ElemType A[ ], int N ) { for ( i = 1; i <= N; i++ ) A[i].P = 1 + rand()%(N3); /* makes it more likely that all priorities are unique */ Sort A, using P as the sort keys; }
Claim: PermuteBySorting produces a uniform random permutation of the input, assuming all priorities are distinct
Online Hiring Algorithm
hire only once
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int OnlineHiring ( EventType C[ ], int N, int k ) { int Best = N; int BestQ = -INFINI ; for ( i = 1; i <= k; i++ ) { Qi = interview( i ); if ( Qi > BestQ ) BestQ = Qi; } for ( i = k+1; i <= N; i++ ) { Qi = interview( i ); if ( Qi > BestQ ) { Best = i; break; } } return Best; }