Binary search algorithm

Source: Internet
Author: User

Binary search, also known as binary lookup algorithm, binary search, is a search algorithm for finding a particular element in an ordered array. The search process begins with the middle element of the array, and if the intermediate element is exactly the element to be found, the search process ends, and if a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning of the intermediate element. If an array of steps is empty, the representation cannot be found. Each comparison of this search algorithm reduces the search scope by half.

1#include <iostream>2 using namespacestd;3 4 intBinarySearch (intKeyintLowintHighConst intarray[])5 { 6      while(Low <=High )7     {8         intMid = low+ (high-low)/2;//should in while9         if(Key >Array[mid])TenLow = mid +1; One         Else if(Key <Array[mid]) AHigh = mid-1; -         Else -             returnmid; the     } -     return-1;//didn ' t find - } -  + /*Recursive version - int BinarySearch (int key, int low, int high,const int arr[]) + { A int mid = low + (high-low)/2;//does not use (Low+high)/2 which might encounter overflow issue at if (Low>high) - return-1; - Else -     { - if (arr[mid] = = key) - return mid; in else if (arr[mid]>key) - return BinarySearch (Key, Low, mid-1, arr); to Else + return BinarySearch (Key, Mid + 1, high, arr); -     } the } * */ $ Panax Notoginseng voidResultinta) - { the     if(A = =-1) +cout <<"BinarySearch failed, not included"<<Endl; A     Else thecout <<"BinarySearch result is an array number"<< a <<Endl; + } - intMain () $ { $     intarray[Ten] = {1,3,5,8, One, +, -, $, $, About }; -     intA = BinarySearch (5,0,9, array); -     intb = BinarySearch (4,0,9, array); the result (a); - result (b);Wuyi     //System ("pause"); the     return 0; -}

Note In a non-recursive version, int mid = low + (high-low)/2; Should be inside the loop.

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.