Transfer from http://zmp1123.blog.163.com/blog/static/1193291592013314581911/
Set n different integers to be stored in t[0:n-1], if there is a subscript i,0≤i<n, yes t[i]=i, design an effective algorithm to find this subscript. The calculation time for the algorithm in the worst case is called O (logn).
The algorithm is described as follows:
Since n integers are different, there are t[i]≤t[i+1]-1 for any 0≤i<n-1.
1 for 0<i<n, when T[i]>i, there is t[j]≥t[i]+j-i>i+j-i=j for any i≤j≤n-2.
2 for 0<i<n, when T[i]<i, to any 0≤j≤i have t[j]≤t[i]-i+j <i-i +j =j.
by ① and ②, we can find the subscript in O (logn) time by using the binary search method.
The algorithm is as follows:
Non-recursive two-part search:
Template<class t>
int BinarySearch (T a[],int left,int right)
{
int middle;
while (Left<=right) {
Middle= (left+right)/2;//middle= (left+right) >>1;
if (Middle==a[middle]) return middle;
if (Middle>a[middle]) left=middle+1;
else right=middle-1;
}
return 0;
}
Recursive two-part search:
Template<class t>
int Findfixedpoint (T a[],int left,int right)
{
int middle;
Middle= (left+right)/2;//middle= (left+right) >>1;
if (left<=right) {
if (Middle==a[middle]) return middle;
else if (Middle>a[middle]) findfixedpoint (a,middle+1,right);
else Findfixedpoint (a,left,middle-1);
}
return 0;
}