簡體   English   中英

Big-O中函數的時間復雜度

[英]Time complexity of a function in Big-O

我正在嘗試查找此函數的時間復雜度:

int bin_search(int a[], int n, int x); // Binary search on an array with size n.

int f(int a[], int n) {
    int i = 1, x = 1;
    while (i < n) {
        if (bin_search(a, i, x) >= 0) {
            return x;
        }
        i *= 2;
        x *= 2;
    }
    return 0;
}

答案是(log n)^ 2。 怎么會?
我能得到的最好是log n 首先, i1 ,因此while將被運行log n次。
在第一次交互時,當i=1 ,二進制搜索將只有一個交互,因為數組的大小為1(i)。 然后,當i=2 ,將進行兩次交互,依此類推,直到log n交互。
所以我認為合適的公式就是這個
求和是針對一會兒的,內部方程式是因為對於i=1它是log(1) ,對於i=2它是log(2) ,依此類推,直到最后一個log(n)

我哪里錯了?

每次迭代都對數組的前2^i元素執行二進制搜索。

您可以計算操作數(比較):

log2(1) + log2(2) + log2(4) + ... + log2(2^m)

log(2^n)等於n ,因此該系列簡化為:

0 + 1 + 2 + ... + m

其中mfloor(log2(n))

該系列的計算結果為m * (m + 1) / 2 ,替換m得到

floor(log2(n)) * (floor(log2(n)) + 1) / 2

->  0.5 * floor(log2(n))^2 + 0.5 * floor(log2(n))

第一個元素主導第二個元素,因此復雜度為O(log(n)^2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM