Binary search algorithm

Source: Internet
Author: User
Tags strcmp

Problem:

Find an ordinal (dictionary-ordered) string array of elements in arr that are equal to the string V, and if more than one element satisfies this condition, returns the largest of the ordinal.

int Bisearch (char** arr, int b, int e, char* v)
{
There are two scenarios for the end of the loop:
If the minindex is an even number minindex==maxindex;
otherwise it is minindex==maxindex-1;
while (minindex<maxindex-1)
{
Midindex = Minindex + (maxindex-minindex)/2;//not Used (Minindex+maxindex)/2 is to avoid overflow
if (strcmp (Arr[midindex], V) <= 0)
Minindex = Midindex;
Else
Maxindex = midindex;//do not need midIndex-1, prevent minindex==maxindex;
}
if (!strcmp (Arr[maxindex], V))//First determine the maximum value of the ordinal
return maxindex;
else if (!strcmp (Arr[minindex], V))
return minindex;
Else
return-1;
}

Binary search algorithm

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.