Algorithm ---- binary search algorithm, algorithm ---- binary

Source: Internet
Author: User

Algorithm ---- binary search algorithm, algorithm ---- binary

Binary Search is a frequently used algorithm in Ordered arrays. When you are not in contact with the binary search algorithm, the most common method is to traverse the array, compare with each element. The time is O (n ). but the binary search algorithm is better, because the search time is O (lgn), such as the Array {1, 2, 3, 4, 5, 6, 7, 8, 9 }, search element 6. If the binary search algorithm is used for execution, the order is as follows:
1. the first step is to find the intermediate element, that is, 5. Because 5 <6, 6 must be included in the array element after 5, so it is searched in {6, 7, 8, 9,
2. Search for the median of {6, 7, 8, 9}, which is 7> 6. Then 6 should be in the array element on the left of 7, and only 6 is left.

The binary search algorithm is to continuously split the array into half, and compare the intermediate elements with the target to be searched each time.

#include <iostream>#include <vector>using namespace std;int binary_search(vector<int> &vec, int value){size_t len = vec.size();int start = 0;int end = len-1;while (start <= end){int mid = (end + start) / 2;if (vec[mid] == value)return mid;else if (vec[mid] > value)end = mid - 1;elsestart = mid + 1;}return -1;}int main(int argc, char*argv[]){int idx = 0;vector<int> vec = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };idx=binary_search(vec, 6);cout << idx << endl;return 0;}

Php code:

function binsearch($x,$a){$c=count($a);$lower=0;$high=$c-1;while($lower<=$high){$middle=intval(($lower+$high)/2);if($a[$middle]>$x)$high=$middle-1;elseif($a[$middle]<$x)$lower=$middle+1;elsereturn $middle;}return -1;}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.