How to calculate the time complexity of the algorithm

Mondo Technology Updated on 2024-01-31

We generally use the "big o symbolic notation" to represent the time complexity: t(n) = o(f(n)) n is the factor that affects the change of complexity, and f(n) is the complexity-specific algorithm.

Constant order o(1) linear order o(n) logarithmic order o(logn) linear logarithmic order o(nlogn) square order o(n) cubic order o(n)k power o(n k) exponential order (2 n).

int a = 1;int b = 2;int c = 3;
for(i = 1; i <= n; i++)
int i = 1;while(i < n)
You can see that i is multiplied by 2 every time you loop, so the total number of loops is log2n, so the time complexity of this ** is o(logn).

for(m = 1; m < n; m++)
The linear logarithmic order o(nlogn) is actually very easy to understand, and if the time complexity is the ** of o(logn) is looped n times, then its time complexity is n * o(logn), which is o(nlogn).

for(x = 1; i <= n; x++)
If you nest the ** of o(n) again, the time complexity of it is o(n).

The number of variables created.

int i = 1;int j = 2;++i;j++;int m = i + j;
int m = new int[n]for(i = 1; i <= n; +i)
In this paragraph, the first row of new an array comes out, and the size of this data is n, although there is a loop later, but no new space is allocated, therefore, the space complexity of this ** mainly depends on the first row, that is, s(n) = o(n).

int binarysearch(int arr,int len, int num) else if (num < arr[mid]) else }return -1;}
In the case of a bipartite search, the original search content is bipartite each time, so the time complexity is o(logn).

Because the variable value is created once, the space complexity is o(1).

int binarysearchrecursion(int arr[5], int lef, int rig,int aim) else if (arr[mid] creates a variable every time recursion is made, so the space complexity is o(log2 n).

int feibonacciinteration(int a,int b,int num) return c; }

Time complexity o(n).

The spatial complexity is o(1).

int feibonaccirecursion(int num)
The time complexity is o(2 n).

The space complexity is o(n).

Related Pages