[Sorting] Binary Search Extension

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.