以下算法返回數組的前一個較大元素。它是從these筆記第11頁。以前的較大元素算法的預期運行時間
// Input: An array of numeric values a[1..n]
// Returns: An array p[1..n] where p[i] contains the index of the previous
// larger element to a[i], or 0 if no such element exists.
previousLarger(a[1..n])
for (i = 1 to n)
j = i-1;
while (j > 0 and a[j] <= a[i]) j--;
p[i] = j;
return p
我的家庭作業的問題是:給定輸入序列{a1,...,an}
是集{1,...,n}
的隨機排列,什麼是預期的運行時間?
我認爲這需要某種概率分析,但我需要一些提示,因爲我以前只做過最壞情況分析。我試圖找到j-loop
對於給定的i(1 +我們操作的次數j--
)的成本公式,然後將該公式從1增加到n。
「預期」是什麼意思?我真的不知道如何解釋這一點。
另一種方法:有n!可能的數組,並且答案將是: E [運行時間] = sum i = 1,...,N! {Runtime(i)}/N! – superquest