# Python implements binary search and python Binary Search

Source: Internet
Author: User

Python implements binary search and python Binary Search

Binary Search Algorithm: Simply put, an array is sorted first, for example, in ascending order. When a data, such as target, when searching for the position of the target in the array, You can first find the number array [middle] in the middle of the array and compare it with the target. When it is smaller than the target, the target must be on the right of the array, on the contrary, the target is on the left side of the array. For example, if it is smaller than the target, you can compare the number of [middle + 1, end] Next time. continue to use the bipartite method to split it into two parts, until the number of target values is found, or the array is completely traversed (the target is not in the array)

Advantage: high efficiency, time complexity is O (logN );
Disadvantage: data is ordered and stored in sequence.

Python code implementation is as follows:

`#!/usr/bin/python env# -*- coding:utf-8 -*-def half_search(array,target):  low = 0  high = len(array) - 1  while low < high:     mid = (low + high)/2     if array[mid] > target:      high = mid - 1     elif array[mid] < target:      low = mid + 1     elif array[mid] == target:      print 'I find it! It is in the position of:',mid      return mid     else:      print "please contact the coder!"  return -1if __name__ == "__main__":  array = [1, 2, 2, 4, 4, 5]`

The running result is as follows:

`I find it! It is in the position of: 44-1I find it! It is in the position of: 00-1`

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Keywords:
Related Article

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.