Why is the time complexity O(n^2) in this code?

蹲街弑〆低调 提交于 2019-12-24 08:18:04

问题


I just didn't get it, why the time complexity is O(n^2) instead of O(n*logn)? The second loop is incrementing 2 each time so isn't it O(logn)?

void f3(int n){
  int i,j,s=100;
  int* ar = (int*)malloc(s*sizeof(int));

  for(i=0; i<n; i++){
    s=0;
    for(j=0; j<n; j+=2){
      s+=j;
      printf("%d\n", s);
  }
  free(ar);
}

回答1:


By incrementing by two, rather than one, you're doing the following N*N*(1/2). With big(O) notation, you don't care about the constant, so it's still N*N. This is because big(O) notation reference the complexity of the growth of an algorithm.




回答2:


Outer loop will execute for n times and for each outer loop iteration inner loop will execute for n/2 times because j +=2

Order = n×n/2 = n^2/2 =O(n^2) because constant doesn't affect run time for large n




回答3:


there is an increment of 2 so loop will runs for n/2.So the complexity will be n*n/2. if increament happened in GP like 2



来源:https://stackoverflow.com/questions/51162446/why-is-the-time-complexity-on2-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!