二分法

要求在一个有序序列中,例如[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99],查找一个数字,如果找到则打印该数字,如果找不到,则输出“not found!”

 

1:递归方式

递归,是在函数中自身调用自身的一种情况,直到有一个明确的退出条件成立后结束相互调用。递归是一种很容易理解某类问题的方式,但是不是特别高效,因为每次调用自身时,都会在内存中创建一个新的内存空间,当不断循环调用非常多次时,是非常耗内存的。

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def recursion_search(data_source, find_n):
    mid = len(data_source) / 2
    if len(data_source) >= 1:
        if find_n > data_source[mid]:
            recursion_search(data_source[mid + 1:], find_n)
        elif find_n < data_source[mid]:
            recursion_search(data_source[:mid], find_n)
        else:
            print data_source[mid]
    else:
        print "not found !"


if __name__ == '__main__':
    test_array = range(0, 100, 3)
    recursion_search(test_array, 99)

2:循环方式

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def loop_search(data_source, find_n):
    while len(data_source):
        mid = len(data_source) / 2
        if find_n < data_source[mid]:
            data_source = data_source[:mid]
        elif find_n > data_source[mid]:
            data_source = data_source[mid + 1:]
        else:
            print data_source[mid]
            break
    else:
        print "not found !"


if __name__ == '__main__':
    test_array = range(0, 100, 3)
    loop_search(test_array, 99)

 

 

2、不能排序直接用二分法求出来最大值的索引值[1,2,4,6,3,1] 

list = [1,2,4,6,3,1]
def twosplit(list,left,right):
    while (left<=right):
        mid  = (left+right)//2
        if list[mid]>list[mid - 1] and list[mid]>list[mid + 1]:
            return mid
        elif list[mid]>list[mid-1] and list[mid]<list[mid + 1]:
            left = mid
        else:
            right = mid

if __name__ =="__main__":
    print(twosplit(list, 0, len(list) - 1))

 

# 给定一个排好序(升序)的列表与待查找的关键字,成功则返回其索引,失败则返回-1。
def search(list, key):
    left = 0     # 左边界
    right = len(list) - 1   # 右边界
    while left <= right:
        mid = (left + right) // 2  # 取得中间索引
        if key > list[mid]:
            left = mid + 1
        elif key < list[mid]:
            right = mid - 1
        else:
            return mid
    else:
        return -1

list = [2, 5, 13, 21, 26, 33, 37]
print(search(list, 21))

 

posted @ 2019-03-20 19:12  lvmenghui001  阅读(265)  评论(0编辑  收藏  举报