Two kinds of implementations of binary lookup method
Binary Lookup Method:
In an ordered table, there are three scenarios where the value of the data to be looked up is compared to the median value of the lookup range:
1) to find the data value exactly equal to the intermediate element value, put back the index of the intermediate element value.
2) The data value to be found is smaller than the middle element value, then the first half of the entire look-up range is used as the new look-up range, and 1 is executed until an equal value is located.
3) The data value to be found is larger than the middle element value, then take the second half of the entire look-up range as the new lookup range, execute 1) until an equal value is found
4) If no equal value is found at the end, an error message is returned.
According to the binary tree to understand: The median is two fork tree root, the first half of the left dial hand tree, the second half is the right sub-tree. The binary lookup is exactly the number of layers where the value is located. In the case of equal probability, about
LOG2 (n+1)-1
[CPP]View Plaincopy
- Data is the array to find, X is the value to look for, beg is the start of the lookup range, and last is the end of the lookup range
- Non-recursive method
- int Bisearch (int data[], const int x, int beg, int last)
- {
- int mid; //Middle position
- if (Beg > last)
- {
- return-1;
- }
- While (Beg <= last)
- {
- Mid = (beg + last)/2;
- if (x = = Data[mid])
- {
- return mid;
- }
- Else if (Data[mid] < x)
- {
- Beg = mid + 1;
- }
- Else if (Data[mid] > x)
- {
- last = mid-1;
- }
- }
- return-1;
- }
- Recursive method
- int Iterbisearch (int data[], const int x, int beg, int last)
- {
- int mid =-1;
- Mid = (beg + last)/2;
- if (x = = Data[mid])
- {
- return mid;
- }
- Else if (x < Data[mid])
- {
- return Iterbisearch (data, x, Beg, mid-1);
- }
- Else if (x > Data[mid])
- {
- return Iterbisearch (data, X, Mid + 1, last);
- }
- return-1;
- }
- Main function
- int _tmain (int argc, _tchar* argv[])
- {
- int data1[60] = {0};
- int no2search = 45;
- cout << "The array is:" << Endl;
- int siz = sizeof (data1)/sizeof (int);
- For (int i = 0; i < siz; i++)
- {
- Data1[i] = i;
- cout << Data1[i] << "";
- }
- cout << Endl;
- int index =-1;
- //index = Bisearch (data1, No2search, 0, siz);
- index = Iterbisearch (data1, No2search, 0, siz);
- cout << "Index of" << no2search << "is" << Index << Endl;
- GetChar ();
- return 0;
- }
Two kinds of implementations of binary lookup method