Implementation of _python by Python binary method

Source: Internet
Author: User

1. Algorithm: ( set to find the array period for Array[low, high])

(1) Determine the middle position of the period K
(2) Compare the lookup value T with Array[k]. If equal, the lookup successfully returns to this location, otherwise the new lookup area is determined, and the binary lookup continues. The region is determined as follows:
A.array[k]>t is known by the order of the array array[k,k+1,......, high]>t; so the new interval is Array[low,......, K-1]
B.array[k]<t similar to the above search range for array[k+1,......, high]. Each lookup is compared to an intermediate value to determine whether the lookup is successful and the current lookup interval is reduced by half. Recursive search, you can.

2.python Code:

Copy Code code as follows:

#!/usr/bin/python
#-*-Coding:utf-8-*-

def binarysearch (array,t):
Low = 0
Height = len (array)-1
While low < height:
Mid = (low+height)/2
If Array[mid] < T:
Low = mid + 1

Elif Array[mid] > t:
Height = mid-1

Else
return Array[mid]

Return-1


if __name__ = = "__main__":
Print BinarySearch ([1,2,3,34,56,57,78,87],57)

Results: 57

3. Time complexity: O (LOG2N);

Note: The premise of the binary lookup must be ordered in order to find the sequence.

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.