简体   繁体   English

Big-O中函数的时间复杂度

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

I'm trying to find the time complexity of this function: 我正在尝试查找此函数的时间复杂度:

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;
}

The answer is (log n)^2. 答案是(log n)^ 2。 How come? 怎么会?
Best I could get is log n . 我能得到的最好是log n First the i is 1 , so the while will be run log n times. 首先, i1 ,因此while将被运行log n次。
At first interaction, when i=1 , the binary search will have only one interaction because the array's size is 1(i). 在第一次交互时,当i=1 ,二进制搜索将只有一个交互,因为数组的大小为1(i)。 Then, when i=2 , two interactions, and so on until it's log n interactions. 然后,当i=2 ,将进行两次交互,依此类推,直到log n交互。
So the formula I thought would fit is this . 所以我认为合适的公式就是这个
The summation is for the while and the inner equation is because for i=1 it's log(1) , for i=2 it's log(2) and so on until it's log(n) at the last. 求和是针对一会儿的,内部方程式是因为对于i=1它是log(1) ,对于i=2它是log(2) ,依此类推,直到最后一个log(n)

Where am I wrong? 我哪里错了?

Each iteration performs a binary search on the first 2^i elements of the array. 每次迭代都对数组的前2^i元素执行二进制搜索。

You can compute the number of operations (comparisons): 您可以计算操作数(比较):

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

log(2^n) equals n , so this series simplifies into: log(2^n)等于n ,因此该系列简化为:

0 + 1 + 2 + ... + m

Where m is floor(log2(n)) . 其中mfloor(log2(n))

The series evaluates to m * (m + 1) / 2 , replacing m we get 该系列的计算结果为m * (m + 1) / 2 ,替换m得到

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

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

The first element dominates the second, hence the complexity is O(log(n)^2) 第一个元素主导第二个元素,因此复杂度为O(log(n)^2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM