Python实现各类数据结构和算法---折半查找

递归和非递归形式实现二分查找

#coding:utf-8
a=[1, 2, 3, 4, 5, 6, 8, 20, 24, 31, 35]
#-----------------递归二分查找------------------
b=10
def binarySearch(array,n,left,right):
    mid=left+(right-left)/2
    if(left>right):
        print 'find failed'
        return -1
    else:
        if(array[mid]>n):
            return binarySearch(array, n, left, mid-1)
        elif(array[mid]<n):
            return binarySearch(array, n, mid+1, right)
        else:
            print 'find it'
            return mid
print binarySearch(a, b, 0, len(a)-1)
#-------------------非递归查找------------------------
c=5
def binary_Search(a,n): 
    low = 0
    high = len(a)-1
    while low <= high: 
        middle = (low+high)/2 
        if a[middle] == n: 
            print 'find it'
            return middle+1 
        elif a[middle] < n:
            low = middle + 1 
        else:
            high = middle - 1 
    print 'find failed'
    return -1

print binary_Search(a,c)

    原文作者:查找算法
    原文地址: https://blog.csdn.net/u010454729/article/details/21194139
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞