1. Practice Title: 7-1
2. Problem Description: Use the binary lookup algorithm to find x in n non-descending integers, the subscript (0~n-1) where x is located, and the number of comparisons. If x does not exist, output-1 and number of comparisons.
3, algorithm Description: n elements are divided into roughly the same number of two halves, take A[mid] and x comparison. If X=a[mid], the x is found, the algorithm terminates, if X<A[MID], only the left half of the array a continues to look for X, if X>a[mid], then only the right half of a continues to search for X. Also, add a B statistic comparison number in the while statement.
4, the code is as follows:
1#include <iostream>2 using namespacestd;3 intBinarySearch (intA[],intLeftintRightintXint&b) { 4 while(left<=Right ) { 5b++;6 intMiddle = (left+right)/2; 7 if(x==A[middle]) { 8 returnMiddle;9 }Ten if(x>A[middle]) { OneLeft=middle+1; A } - Else { -Right =middle-1; the } - } - return-1; - } + intMain () { - intn,x,b=0; +Cin>>N; A inta[ +]; at for(intI=0; i<n;i++){ -Cin>>A[i]; - } -Cin>>x; - intIndex=binarysearch (A,0, N-1, x,b); -cout<<index<<endl<<b; in}
5. Time Complexity and space complexity: using the two-method search algorithm, the time complexity of searching for X is O (Logn), and the spatial complexity is a constant, which is independent of the value of variable N. So the spatial complexity is O (1).
6, Experience: to flexibly use the code learned, they are flexibly embedded in the problem to be solved. In solving the problem, we should consider the optimal solution, which is the least time complexity solution, which is advantageous to make the algorithm more convenient and the resources can be used rationally.
The second chapter on the Computer Experiment report