Find the sequence number of the element where the value of ARR in an ordered string array is equal to the value of string v. If multiple elements meet this condition, what is the maximum number returned?
Similarly, if multiple elements meet this condition, the minimum sequence number is returned?
# Include <iostream>
Using namespace STD;
Int binary_search (int * arr, int Len, int key)
{
If (ARR = NULL | Len <= 0)
Return-1;
Int minindex = 0, maxindex = len-1, midindex;
// There are two cases of loop end: If minindex is an even number, minindex = maxindex; otherwise, minindex = maxindex-1
While (minindex <maxIndex-1)
{
Midindex = minindex + (maxindex-minindex)/2;
If (ARR [midindex]> = key)
Maxindex = midindex;
Else
Minindex = midindex; // do not need midindex + 1 to prevent minindex = maxindex
}
If (ARR [minindex] = key)
Return minindex;
Else if (ARR [maxindex] = key)
Return maxindex;
Return-1;
}
Int main ()
{
Const int size = 10;
Int arr [size], key;
Cout <"input sorted array :";
For (INT I = 0; I <size; I ++)
Cin> arr [I];
Cout <"key :";
Cin> key;
Cout <binary_search (ARR, size, key) <Endl;
Return 0;
}
//-5-5-5-5-5-5-5-5-5-5-5
//-6-2-1 5 5 6 7 8 9
//-6-2 5 5 5 6 7 8 9