[英]Is the time complexity of this function O(N)?
What is the time complexity of this function? 该函数的时间复杂度是多少? The function returns minimum value in the array.
该函数返回数组中的最小值。 I think it's
O(N)
but I can't prove it. 我认为这是
O(N)
但我无法证明。 Any help would be appreciated! 任何帮助,将不胜感激!
int[] foo(int arr[], int N)
{
int k = 1;
while(k < N)
{
for(int i = 0; i+k<N; i+=2*k)
{
if(arr[k] > arr[i+k])
{
swap(arr[i], arr[k+i]); //swap values in arr[i] and arr[k+1]
}
}
k = k*2;
}
return arr[0];
}
It's O(N)
. 是
O(N)
。
It may seem like O(NlogN)
at a first glance, but: 乍一看似乎是
O(NlogN)
,但:
i = 0, 2, 4, 6, 8, ...
ie N/2
operations i = 0, 2, 4, 6, 8, ...
即N/2
操作 i = 0, 4, 8, 12, 16, ...
ie N/4
operations i = 0, 4, 8, 12, 16, ...
即N/4
操作 i = 0, 8, 16, 24, 32, ...
ie N/8
operations i = 0, 8, 16, 24, 32, ...
即N/8
操作 i = 0, 16, 32, 48, 64, ...
ie N/16
operations i = 0, 16, 32, 48, 64, ...
即N/16
操作 N/2 + N/4 + N/8 + N/16 + ... = N(1/2 + 1/4 + 1/8 + 1/16 ...) = N
https://en.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%E2%8B%AF https://zh.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%E2%8B%AF
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.