Binary search algorithm

Source: Internet
Author: User

Binary search algorithm is a more frequent algorithm used in an ordered array, the most common way to do this is to traverse the array, compare each element, and the time is O (n). But the binary lookup algorithm is better because it has a lookup time of O (log n)

Sample Input

4//要查找的数6//数组长度1 4 5 7 9 12

Sample Output

1//返回下标值

1 #include <cmath>2 #include <cstdio>3 #include <vector>4 #include <iostream>5 #include <algorithm>6UsingNamespaceStd78int Binary_search (vector<Int> A,int Len,IntGoal) {9int low =0;10int high = Len-1;11while (Low <=High) {12int mid = (high-low)/2 + low;//Direct use (high + low)/2 may cause overflow13if (Goal = =A[mid])14ReturnMid15//On the left half16Elseif (Goal <A[mid])-High = mid-1;18//On the right half19ElseLow = mid +1;21st}22//Didn't find23Return-1;24}2526IntMain () {27IntV, N;Cin >> v >>Nvector<Int>AR (n);30Forint i =0; I < n; i++){>> CINAr[i];32}33int index = Binary_search (AR, n, v); 34 35 if (Index! =-1< Span style= "color: #000000;" >) 36 cout << index << Endl;37 else38 cout <<  " no " << v < <endl; return 0;40 41}           

Binary Lookup 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.