Binary lookup is a more efficient way to find, the basic idea is: in an ordered table, take the intermediate record as the comparison object, if the key code to find the record is equal to the key code of the intermediate record, then the search succeeds; to find the key code of the record that is less than the middle record, continue looking in the left half of the intermediate record If the key code for the lookup record is greater than the key code for the intermediate record, the search continues in the right half of the intermediate record. The lookup process continues to repeat until the lookup succeeds, or the ordered table does not have the records to look for, and the find fails. There are two ways to implement the recursive method and the non-recursive method.
1. Non-recursive method: The lookup succeeds then returns the position, the lookup fails the range-1.
/////////////////////////////////////////////////
Non-recursive lookup 1. Numvec for the set to be found 2.x for the value to be found 3.beg for the lookup range start 4.last for the search range end
/////////////////////////////////////////////////
int Bisearch::bisearch (vector<int> numvec,int x,int Beg,int last) {
int mid;//Middle Position
if (beg>last) {//beg start position is greater than last end position, currently only consider ascending state
return-1;
}
while (Beg<=last) {
Mid = (beg+last)/2;
if (X==numvec[mid]) {//x (key code) is exactly the same as the median (Numvec[mid])
return mid;
}else if (X>numvec[mid]) {//x (key code) is greater than the median (Numvec[mid]), the starting point is anchored to mid+1
Beg = Mid +1;
}else if (X<numvec[mid]) {//x (key code) less than median (Numvec[mid]), end position to Mid-1
last = mid-1;
}
}
return-1;
}
2. Recursive method:
int Bisearch::iterbisearch (vector<int> numvec,int x,int Beg,int last) {
Intermediate position initialized to-1
int mid =-1;
Mid = (beg+ last)/2;
if (X==numvec[mid]) {
return mid;
}else if (X<numvec[mid]) {
Return Iterbisearch (numvec,x,beg,mid-1);
}else if (X>numvec[mid]) {
Return Iterbisearch (Numvec,x,mid+1,last);
}
return-1;
}
Binary Search Algorithm implementation