zoukankan      html  css  js  c++  java
  • python递归实现折半查找

    1.Python 基础教程版:(有点没想清楚)

     1 def search(sequence, number, lower=0, upper=None):
     2     if upper is None: upper = len(sequence) -1
     3     print 'sequence = ', sequence, 'number = ' , number,
     4           'lower = ', lower, 'upper = ', upper
     5     if lower == upper:
     6         assert number == sequence[upper]
     7         return upper
     8     else:
     9         middle = (lower + upper) // 2
    10         if number > sequence[middle]:
    11             return search(sequence, number, middle + 1, upper)
    12         else:
    13             return search(sequence, number, lower, middle)

    2.自己实现版:

     1 def search(sequence, number, lower=0, upper=None):
     2     if upper is None: upper = len(sequence) -1
     3     print 'sequence = ', sequence, 'number = ' , number,
     4           'lower = ', lower, 'upper = ', upper
     5     if lower > upper:
     6         #assert number == sequence[upper]
     7         print 'number is not in sequence'
     8         return -1
     9     else:
    10         middle = (lower + upper) // 2
    11         if number == sequence[middle]:
    12             return middle
    13         elif number > sequence[middle]:
    14             return search(sequence, number, middle + 1, upper)
    15         else:
    16             return search(sequence, number, lower, middle - 1)
    17 
    18 def main():
    19     seq = [34, 67, 8, 123, 4, 100, 95, 175]
    20     seq.sort()
    21     print 'seq = ', seq
    22     n = input('please input a number from list:')
    23     print search(seq, n)
    24 
    25 if __name__ == '__main__':
    26     main()
  • 相关阅读:
    UVa 116 单向TSP(多段图最短路)
    POJ 1328 Radar Installation(贪心)
    POJ 1260 Pearls
    POJ 1836 Alignment
    POJ 3267 The Cow Lexicon
    UVa 1620 懒惰的苏珊(逆序数)
    POJ 1018 Communication System(DP)
    UVa 1347 旅行
    UVa 437 巴比伦塔
    UVa 1025 城市里的间谍
  • 原文地址:https://www.cnblogs.com/yunsicai/p/3833584.html
Copyright © 2011-2022 走看看