Python implementation of a binary algorithm example

Source: Internet
Author: User
1. Algorithm: (set to find the array period of array[low, high])

(1) Determine the intermediate position of the period K
(2) Compare the lookup value T with Array[k]. If it is equal, the lookup returns to this location successfully; otherwise, identify the new lookup area and continue with the binary lookup. The region is determined as follows:

A.array[k]>t by the order of the array array[k,k+1,......, high]>t; The new interval is Array[low,......, K-1]
B.ARRAY[K]

The code is 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 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.