Binary search algorithm

Source: Internet
Author: User

Binary search algorithm is one of the more frequent algorithms used in ordered arrays, in the non-contact binary lookup algorithm, the most common approach is to traverse the array, compare each element, and its time is O (n). But the binary lookup algorithm is better because it has a lookup time of O (LGN), such as the array {1, 2, 3, 4, 5, 6, 7, 8, 9}, find element 6, executed with binary lookup algorithm, in the order of:
1. The first step is to find the intermediate element, that is, 5, because 5<6, 6 is necessarily in the array element after 5, then it is found in {6, 7, 8, 9},
2. Looking for the median of {6, 7, 8, 9}, which is 7,7>6, 6 should be in the array element to the left of 7, then only 6 is found.

The binary search algorithm is to continuously divide the array into half, and compare the intermediate elements with goal each time.

1#include <iostream>2 using namespacestd;3 4 //Two-point search5 intBinary_search (intAintLenintgoal);6 7 intMain ()8 {9     Const intLEN =10000;Ten     intA[len]; One      for(inti =0; i < LEN; i++) AA[i] = i- the; -     intGoal =0; -     intindex =Binary_search (A, LEN, goal); the  -     if(Index! =-1) -cout<<goal<<"The subscript in the array is"<<binary_search (A, LEN, goal) <<Endl; -     Else +cout<<"does not exist"<<goal<<Endl; -     return 0; + } A  at intBinary_search (intAintLenintgoal) - { -     intLow =0; -     intHigh = Len-1; -      while(Low <=High ) -     { in         intMiddle = (low + high)/2; -         if(A[middle] = =goal) to             returnMiddle; +         //on the left half -         Else if(A[middle] >goal) theHigh = middle-1; *         //on the right half $         ElsePanax NotoginsengLow = middle +1; -     } the     //didn't find +     return-1; A}

This article transferred from: http://www.cnblogs.com/shuaiwhu/archive/2011/04/15/2065062.html

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.