This is the fourth chapter in programming:
If the first binary search is too simple for you (everyone must feel this way...), please give it a try:In p, return the position where t appears for the first time in array x (that is, if an array appears multiple times, the original algorithm returns any of the many positions ).Your code should compare the logarithm of the array elements. It may take log2N to complete this binary search.
The key to this question is to find the first place to appear, such as for the array: {0, 5, 5, 5, 14, 16, 16, 50, 65, 70 };
If the previous binary search algorithm is used:
But we can see that 5 is in the arrayThe second position (of course, the subscript of the array is 1 );
First, the algorithm goes through binary search. First, mid = (low + high) = 5; 14 is found, and x <a [mid]; high = mid-1 = 4;
Mid = 2; at this time, 5 is found, and the final output 5 is the third (mid + 1) in the array (the array starts with the subscript 0, so don't mix it up ...)
But now we need to find the first appearance, that is, before:
if(s[mid] == x) return mid;
At this time, the mid is not returned, because we cannot confirm whether it is the first occurrence;
In this case, the binary search should continue until the matching conditions are not found:
That is:
Int mid; int index =-1; while (low <= high) {mid = (low + high)/2; // binary search if (s [mid] = x) // find the target data {index = mid; // record subscript high = mid-1; // continue the forward match. Can you continue to find} else if (s [mid] <x) low = mid + 1; else high = mid-1;} return index;
Create a subscript index for the tag. The initial value is-1. If the target data is found, modify the index;
The last return value of the index is the first value:
# Include
# Include
Using namespace std; int BinarySearch (int * s, int x, int low, int high) {int mid; int index =-1; while (low <= high) {mid = (low + high)/2; // binary search if (s [mid] = x) // find the target data {index = mid; // record subscript high = mid-1; // continue the forward match, whether to continue to find} else if (s [mid] <x) low = mid + 1; else high = mid-1;} return index;} int main () {int s [] = {0, 5, 5, 5, 5, 14, 16, 34, 50, 65, 70}; // incremental sequence, you can also use dynamic arrays to store data cout <"Enter the number to be searched:"; int num; cin> num; int n = sizeof (s)/sizeof (int); int index = BinarySearch (s, num, 0, n-1); if (index> = 0) // judge whether cout is in the Array Based on the return value <"digit" <