[关闭]
@Scrazy 2016-11-29T12:33:46.000000Z 字数 1986 阅读 955

二分法查找

python


二分法查找,顾名思义,二分、二分就是分成两半呗。(有的翻译是折半法搜索比如SICP里翻译的就是折半法搜索)。它的复杂度为O(logn),在列表(已排序)中对给定值value进行查找并输出其索引(index)值。

  1. # -*- coding: utf-8 -*-
  2. def binary_search(lst, value):
  3. left, right = 0, len(lst) - 1
  4. while left <= right:
  5. middle = int((left + right) / 2) # 取`lst`中值索引
  6. if value > lst[middle]:
  7. left = middle + 1 # value大于`lst`中值,让左边界等于 middle + 1
  8. elif value < lst[middle]:
  9. right = middle - 1 # 类似上
  10. else:
  11. return "The value's index is {}".format(middle)
  12. return "There is no {}".format(value)
  13. if __name__ == '__main__':
  14. lst = [1, 3, 5, 7, 9]
  15. value = int(input("Please input the value(1-10): "))
  16. print(binary_search(lst, value))

再来个递归(recursion)版的吧, 不作过多解释啦!

  1. # -*- coding: utf-8 -*-
  2. def binary_search_rec(lst, value, left, right):
  3. middle = int((left + right) / 2)
  4. if left > right:
  5. return "I'm sorry, there is no {}".format(value)
  6. if value < lst[middle]:
  7. return binary_search_rec(lst, value, left, middle - 1)
  8. elif value > lst[middle]:
  9. return binary_search_rec(lst, value, middle + 1, right)
  10. else:
  11. return "Congratulations, the value's({}) index is {}".format(value, middle)
  12. if __name__ == '__main__':
  13. lst = [1, 3, 5, 7, 9]
  14. left, right = 0, len(lst)
  15. value = int(input("Please input the value: "))
  16. print(binary_search_rec(lst, value, left, right))

没事。温习以下二分搜索!

被拼写错误折磨了一晚上。好好的lft被我写成ltf。debug生无可恋!

  1. from random import randrange
  2. def binary_search(seq, sit, lft, rgt):
  3. mid = (lft + rgt) // 2
  4. if lft > rgt:
  5. return 'The seq no {}'.format(sit)
  6. if sit > seq[mid]:
  7. return binary_search(seq, sit, mid+1, rgt)
  8. elif sit < seq[mid]:
  9. return binary_search(seq, sit, lft, mid-1)
  10. else:
  11. return 'The {} in the seq and the station is {}'.format(sit, mid)
  12. if __name__ == '__main__':
  13. seq = [1, 4, 6, 8, 9, 12, 44, 56]
  14. lft, rgt = 0, len(seq)
  15. print(binary_search(seq, 4, lft, rgt))

昨天面试,面试官出了一道算法题:

有一个数组,其内元素先递增后递减,请找出其中的最大值.

对于我来说,当时第一个想起来的是,排序但是转念间就知道肯定不是最好的啦.于是就在哪儿想啊想,还是想不起来.气氛挺尴尬的,外面也挺冷的(电话面试,外面安静).我想不起来,面试小哥也不急着催我,最后也算是在小哥的提示下,想起了怎么做啦!(太感谢小哥啦, 小哥好人! 喂, 你们几个不许笑啊喂!)

当然是二分啦,下面是算法实现!

  1. # coding=utf-8
  2. def search_max_num(seq, left, right):
  3. mid = (right + left) // 2
  4. if left > right:
  5. return seq[mid]
  6. if seq[mid] > seq[mid - 1]:
  7. return search_max_num(seq, mid + 1, right)
  8. else:
  9. return search_max_num(seq, left, mid - 1)
  10. if __name__ == "__main__":
  11. seq = [32, 55, 54, 54, 54, 54, 32, 15, 6, 4, 2, 1]
  12. print(search_max_num(seq, 0, len(seq)))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注