Set n different integers to be stored in T[1..N], if there is a subscript I (1≤i≤n), so that t[i]=i. Try to design an effective algorithm to find this subscript, the algorithm in the worst case of the calculation time is O (log n)

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.