查找----python

class Solution:
    #顺序查找
    def seq_search(self,list,num):
        for i in(range(len(list))):
            if list[i] == num:
                return i
        return -1

    #二分查找
    #每次能够排除掉一半的数据,查找的效率非常高,但是局限性比较大。
    #必须是有序序列才可以使用二分查找。

    #1、非递归算法
    def binary_search_normal(self,list,num):
        left=0
        right = len(list)-1
        mid = (left+right)//2
        while left <=right:
            if list[mid] > num:
                right = mid-1
                mid = (left+right)//2
            elif list[mid] < num:
                left = mid+1
                mid = (left + right)//2
            else:
                return mid
        else:
            return -1

    #2、递归算法
    def binary_search_re(self,list,num,left,right):
        if left > right:    #递归结束条件
            return -1
        mid = (left+right)//2
        if list[mid] > num:
            right = mid - 1
        elif list[mid] < num:
            left = mid + 1
        else:
            return mid
        return solution.binary_search_re(list, num, left, right)





if __name__ == '__main__':
    list = [3,5,11,17,21,23,28,30,32,50,64,78,81,95,101]
    num = 32
    solution = Solution()
    # result1 = solution.seq_search(list,num)
    # print(result1)
    list.sort()
    # result2 = solution.binary_search_normal(list,num)
    # print(result2)
    result3 = solution.binary_search_re(list,num,0,len(list)-1)
    print(result3)

 

posted @ 2020-03-09 21:59  图图图图胡图图  阅读(392)  评论(0编辑  收藏  举报