I have a doubt consider the case where,
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<"Hi";
}
}
In the above case, we can simply say that the time complexity of our program is O(N^2)
, since the inner loop is running n
times for each value of i
hence the total time complexity will be O(N^2)
.
Now consider the case where,
for(int i=N;i>0;i=i/2;){
for(int j=0;j<i;j++){
// Something
}
}
Here in the above segment of the code, how do we compute the time complexity? If we do the traditional method. It would come out to be O(NLogN)
as the outer loop will run O(LogN)
times and for each value of i
the inner loop will run O(N)
times but which isn’t the actual answer.
Thanks.