Python implements a binary algorithm example

  • 2020-04-02 14:34:21
  • OfStack

1. Algorithm :(set the period of the array searched as array[low, high])

(1) determine the intermediate position K during the period
(2) compare the value T to array[k]. If equal, the search returns this position; Otherwise, determine a new search area and continue binary search. The region is determined as follows:

A.a rray [k] > Array [k,k+1... high] > T; So the new interval is array[low... K-1]
B.a rray [k] < T is similar to the search interval above for array[k+1,..., high]. Each time the search and the middle value comparison, you can determine whether the search is successful, not successful the current search interval reduced by half. Recursively.


#!/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 search must wait for the search sequence to be ordered.


Related articles: