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()