This article mainly introduces the implementation code of the python binary method.
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]
2. python code:
The 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.