Python binary implementation example

Source: Internet
Author: User

1. algorithm :(Array [low, high])

(1) determine the intermediate position K in the period
(2) Compare the searched value T with array [k. If they are equal, the location is returned if the search is successful. Otherwise, the new search area is determined and the binary search is continued. The region is determined as follows:
A. array [k]> T the order of the array shows that array [k, k + 1 ,......, High]> T; so the new range is array [low ,......, K-1
B. array [k] <T is similar to the preceding search range: array [k + 1 ,......, High]. You can check whether the search is successful and the current search interval is halved if the search is unsuccessful. Recursive search.

2. python code:

Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-

Def BinarySearch (array, t ):
Low = 0
Height = len (array)-1
While low 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)

Result: 57

3. Time Complexity: O (log2n );

Note: The sequence to be searched must be ordered on the premise of binary search.

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.