zoukankan      html  css  js  c++  java
  • 递归二分法和另类二分法(不推荐,因为占用资源)

    普通递归版本二分法

    def binary_search(n, left, right):

        if left <= right:

            middle = (left+right) // 2

            if n < lst[middle]:

                right = middle - 1
            elif n > lst[middle]:

                left = middle + 1

            else:

                return middle

            return binary_search(n, left, right)    # 这个return必须要加. 否则接收 到的永远是None.

        else:

            return -1

    print(binary_search(567, 0, len(lst)-1))

    另类二分法(很难计算位置):

    def binary_search(ls, target):

        left = 0

        right = len(ls) - 1

        if left > right:

            print("不在这里")

        middle = (left + right) // 2

        if target < ls[middle]:

            return binary_search(ls[:middle], target)

        elif target > ls[middle]:

            return binary_search(ls[middle+1:], target)

        else:

            print("在这⾥里里")

    binary_search(lst, 567)

  • 相关阅读:
    Tree UVA
    stringstream的使用
    Trees on the level UVA
    strchr和strstr函数
    sscanf的用法
    Dropping Balls UVA
    Boxes in a Line UVA
    Broken Keyboard (a.k.a. Beiju Text) UVA
    Matrix Chain Multiplication (堆栈)
    出栈次序
  • 原文地址:https://www.cnblogs.com/steve214/p/9911838.html
Copyright © 2011-2022 走看看