Accurate binary search and Binary Search

Source: Internet
Author: User

Accurate binary search and Binary Search

Accurate Binary Search

It is important to accurately write binary search, because many of them are prone to errors.


There are mainly the following points:

  • The initial value of right is num-1;
  • Right = middle-1 each update;
  • Every update of middle is left + (right-left)> 1). Note that the shift and shift operators are enclosed in brackets!


The correct procedure is as follows:


# Include <iostream> using namespace std; int isFinded (int * a, int num, int value) {int left = 0, right = num-1; int middle; while (left <= right) {middle = left + (right-left)> 1); if (a [middle] <value) left = middle + 1; else if (a [middle]> value) right = middle-1; elsereturn middle; // returned location} return-1; // not found} int main () {int a [5] = {1, 3, 5, 7, 9}; int num = 5; int value = 5; int finded = isFinded (a, num, value); cout <finded <endl; return 0 ;}


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.