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.