Python implementation of binary search (recursive version)

Binary search
  • Why use a binary search:
    List python in general value to walk through the list until you get to the value you want 但是如果你的列表是一个有着百万元素的列表呢, as for looping through the list will be very slow and may cycle hundreds of thousands of times, you need to find the corresponding value, as a waste of resources is not very well, so in order to more quickly find the corresponding value and save system resources, someone invented the dichotomy algorithm.
  • Principle :
    注意:binary search must be an ordered list can be incremented or decremented, but it must be an ordered list.
    Binary search is also called 折半查找, is a high efficient search method, first of all, assuming that elements in the table are in ascending order arrangement, the keyword table> intermediate position search key and record comparison, if the two are equal, then the lookup is successful; otherwise the position of the recording by the intermediate table> into the front, the two sub-tables, if the record key intermediate position greater than the search key, then look further before a child table, otherwise> further search after a child table. The process is repeated until the record satisfies the condition is found, the search is successful, or until the child table does not exist>, at which time search is unsuccessful
  • python code implements (recursively)
def binary_Search(Array, num,small_num=None,high_num=None):
    small_num = small_num if small_num else 0
    high_num = high_num if high_num is not None else len(Array) - 1
    mid_num = (high_num + small_num) // 2
    if small_num <= high_num:
            if num > Array[mid_num]:return binary_Search(Array,num,mid_num+1,high_num)
            elif num < Array[mid_num]:return  binary_Search(Array, num, small_num,mid_num-1)
            else :return mid_num
    else:
            return '%s值不存在'%num
lis = [99, 222, 444, 544, 555, 567, 777, 786, 787, 991, 998, 5555, 8877]
ret = binary_Search(lis,555)
print('索引值为%s,对应值为%s'%(ret,lis[ret]))

Guess you like

Origin www.cnblogs.com/Hybb/p/11518909.html