#include <iostream>
using namespace Std;
Choose the strategy of dichotomy, find out the range of a number, for example, the range of 2,4,8,12,15,20,23,56,79,90 16 is 15 20.
/** find the first number larger than key, the smallest number larger than key **/
int findright (int data[],int low,int high,int key)
{
int Up=high;
int mid;
while (Low
{
Mid= (Low+high)/2;
if (Data[mid]<=key)
low=mid+1;//the answer must be larger than key, so the nether must be on the right side of mid.
Else
High=mid; Key<data[mid] The answer may be in mid, or on the left of mid, as small as possible, to the left.
}
if ((High==low) && (high==up) && (Key>data[up]))
extern unsigned int strlen (char *s), until it encounters the first string terminator ' \ n ', and then returns the counter value (length does not include "/").
return-1;
Else
return low;
}
Find the maximum number smaller than key
int findleft (int data[],int low,int high,int key)
{
int down=low;
if (Key<data[down])//Depending on the source data situation, both exits are possible, can only be judged in advance
return-1;
int mid;
while (Low+1!=high&&low!=high)//have two exits
{
Mid= (Low+high)/2;
if (Data[mid]>=key)
high=mid-1;//to search for the answer must be smaller than key, so the nether must be on the left of mid
Else
Low=mid; Key>data[mid] The answer may be in mid, or on the right side of mid, as far as possible to the right, looking for a large number
}
if (Low+1==high)//If not added, there will be a dead loop
{
if (Key>data[high])
return high;
else if (Key>data[low])
return low;
}
Else
if (Low==high)
return low;
}
int main ()
{
int data[]= {2,4,8,12,15,20,23,56,79,90};//measured boundary value
int key;
cout<< "Please enter a number;";
cin>>key;
cout<<endl;
int Larger=findright (Data,0,5,key);
if (larger==-1)
cout<< "The number you entered is too big! "<<endl;
Else
cout<< "Right boundary for:" <<data[larger]<<endl;
int Key2;
cout<< "Please enter a number;";
cin>>key2;
cout<<endl;
int Smaller=findleft (DATA,0,9,KEY2);
if (smaller==-1)
cout<< "The number you entered is too small! "<<endl;
Else
cout<< "left boundary for:" <<data[smaller]<<endl;
return 0;
}
Find the range of a number by two points