intHiring(EventTypeC[],intN){/* candidate 0 is a least-qualified dummy candidate */intBest=0;intBestQ=thequalityofcandidate0;for(i=1;i<=N;i++){Qi=interview(i);/* Ci */if(Qi>BestQ){BestQ=Qi;Best=i;hire(i);/* Ch */}}returnBest;}
其中,若 candidate 的质量呈递增分布,则该算法所得的 cost 将是最坏情况;若 candidate 随机分布,则 candidate i 在前 i 个人中最优的概率为 \(\frac{1}{i}\) ,分析计算平均 cost:
\[ \begin{array}c X_i =\begin{cases}1, & \text{if hired} \\ 0, & \text{if NOT hired}\end{cases} \\ \Rightarrow X=\sum X_i, \ E[X_i] =Pr[\text{candidate i is hired}]=\frac{1}{i} \\ \Rightarrow E[X] =E\left[\sum X_i\right]= \sum E[X_i] =\sum_{i=1}^N \frac{1}{i} = \ln N +O(1) \end{array} \]
intRandomizedHiring(EventTypeC[],intN){/* candidate 0 is a least-qualified dummy candidate */intBest=0;intBestQ=thequalityofcandidate0;randomlypermutethelistofcandidates;// How to do it???for(i=1;i<=N;i++){Qi=interview(i);/* Ci */if(Qi>BestQ){BestQ=Qi;Best=i;hire(i);/* Ch */}}}
// A feasible function to make randomized inputvoidPermuteBySorting(ElemTypeA[],intN){for(i=1;i<=N;i++)A[i].P=1+rand()%(N3);/* makes it more likely that all priorities are unique */SortA,usingPasthesortkeys;}