1. Practice title: Two-point search
2. Problem Description: Enter n values (1<=n<=1000), n non-descending integers, and x to find, use binary lookup algorithm to find x, Output x subscript (0~n-1), and number of comparisons. If x does not exist, output-1 and number of comparisons.
3. Algorithm Description:
#include <iostream>
using namespace Std;
int count=0;
int binarysearch (int a[],int left, int. right, int x) {
count++;
if (left==right&&a[left]!=x) {
return-1;
}
else{
int mid = (left+right)/2;
if (a[mid]==x) {
return mid;
}
if (X>mid) {
return BinarySearch (A,MID+1,RIGHT,X);
}
else{
return BinarySearch (A,LEFT,MID-1,X);
}
}
}
int a[1005];
int main () {
int x,n;
cin>>n;
for (int i=0;i<n;i++) {
cin>>a[i];
}
cin>>x;
int ans;
Ans = BinarySearch (a,0,n-1,x);
cout<<ans<<endl<<count;
return 0;
}
4, algorithm time and spatial complexity analysis (to have the analysis process)
Because a binary lookup excludes half of the unsuitable values each time, the case for n elements:
One minute left: N/2
Two second points left: N/2/2 = N/4
。。。
M-second two points left: n/(2^m)
In the worst case, the result is excluded until the last value is left, which is thought to be
n/(2^m) = 1;
2^m=n;
So the complexity of time is: log2 (n)
Because the auxiliary space is constant level, the spatial complexity is O (1);
5, experience (to this practice harvest and doubts to summarize)
This practice let me more clearly understand the two-point search algorithm and the idea of division, before the binary search code implementation is also confused, after this practice, there is a clear concept. Two-point search through continuous binary reduce the number of comparisons, has been relatively good time complexity, this is the harvest in this practice. In this paper, the realization of recursive code has been solved after this practice.
The second chapter on the Computer Experiment report