Binary search algorithm

Source: Internet
Author: User

The binary search algorithm is to continuously divide the array into half, and compare the intermediate elements with goal each time.#include <iostream>
using namespace Std;

Two-point Search
int Binary_search (int* A, int len, int goal);

int main ()
{
const int LEN = 10000;
int A[len];
for (int i = 0; i < LEN; i++)
A[i] = i-5000;
int target = 0;
int index = Binary_search (A, LEN, target);

if (Index! =-1)
cout<<target<< "Subscript in Array" <<index<<endl;
Else
cout<< "does not exist" <<target<<endl;
return 0;
}

int Binary_search (int* A, int len, int goal)
{
int low = 0;
int high = len-1;
while (Low <= high)
{
int middle = (high-low)/2 + low; Direct use (high + low)/2 may cause overflow
if (a[middle] = = goal)
return middle;
On the left half
else if (A[middle] > goal)
High = middle-1;
On the right half
Else
Low = middle + 1;
}
Didn't find
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.