简体   繁体   English

这个函数的时间复杂度是否为O(N)?

[英]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) ,但:

  • 1st inner for loop: i = 0, 2, 4, 6, 8, ... ie N/2 operations 第一个内部for循环: i = 0, 2, 4, 6, 8, ...N/2操作
  • 2nd inner for loop: i = 0, 4, 8, 12, 16, ... ie N/4 operations 第二个内部for循环: i = 0, 4, 8, 12, 16, ...N/4操作
  • 3rd inner for loop: i = 0, 8, 16, 24, 32, ... ie N/8 operations 第三个内部for循环: i = 0, 8, 16, 24, 32, ...N/8操作
  • 4th inner for loop: i = 0, 16, 32, 48, 64, ... ie N/16 operations 第四个内部for循环: i = 0, 16, 32, 48, 64, ...N/16操作
  • etc. 等等

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.

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