A. Time complexity
Definitions: In one process algorithm, the required run-time, generally expressed O.
Use the following search algorithm as an example to illustrate the complexity of the time
Question: give you an array (sorted) to find a given element, output index.
Method One: Direct Anzhi inquiry
void serach(int a[],int b,int n) { for(int i = 0;i<n;i++) { if(a[i] == b) cout<<i<<endl; } }
Where n is the length of the array, we can see the time complexity of this approach is to iterate O (n)
Method Two: binary search
void Binary_Serach(int a[],int b,int n) { int mid,left=0,right=n; bool flag = false; while(left<=right) { mid = (left+right)/2; if(a[mid]==b){ flag = true; cout<<mid<<endl; } if(a[mid]<b) { left = mid+1; } else{ right = mid-1; } } if(flag == false) { cout<<"没找到!"<<endl; } }
A binary search has been taken for finding half way, i.e. 2 X = n-, where X is the time complexity. O = X (log 2 n-)
The time complexity is used to measure whether a program good way.
II. Space complexity
Definition: complete removal of the outer space of the input and output program requires.
Generally, we declare a variable space complexity is a constant order, declare a one-dimensional array do not know the size of the space complexity is O (n).
We usually use space for time in the process of writing the algorithm.