我正在嘗試推導確定性線性搜索算法的平均個案運行時間。該算法以A [1],A [2],A [3] ... A [n]的順序搜索未排序數組A中的元素x。它在找到元素x或停止直到到達數組的末尾時停止。我搜索了wikipedia,給出的答案是(n + 1)/(k + 1),其中k是數組x中存在的次數。我以另一種方式接近並得到不同的答案。任何人都可以請給我正確的證明,並讓我知道我的方法有什麼問題嗎?線性搜索算法的平均個案運行時間
E(T)= 1*P(1) + 2*P(2) + 3*P(3) ....+ n*P(n) where P(i) is the probability that
the algorithm runs for 'i' time (i.e. compares 'i' elements).
P(i)= (n-i)C(k-1) * (n-k)!/n!
Here, (n-i)C(k-1) is (n-i) Choose (k-1). As the algorithm has reached the ith
step, the rest of k-1 x's must be in the last n-i elements. Hence (n-i)C(k-i).
(n-k)! is the total number of ways of arranging the rest non x numbers, and n!
is the total number of ways of arranging the n elements in the array.
關於簡化,我沒有得到(n + 1)/(k + 1)。
也許我是個笨蛋,但是如果數組大小爲N,那麼不是平均情況時間N/2? Nevermind ...不應該從我的iPhone發表評論...誤讀了q – Kevin
@kevin它沒有重複的情況。但是當你有重複時,即使你發現第二次出現(爲了計算平均複雜度),你將首先在你的搜索中獲得。 – Zimbabao
@Kevin實際上沒有多重拷貝情況的平均情況是(n + 1)/ 2。它可以這樣得到:1 *(1/n)+ 2 *(1/n)+ 3 *(1/n)... + n *(1/n)。 – Brahadeesh