Binary Search using Python

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Search using Python相关的知识,希望对你有一定的参考价值。

 1 def binary_search(needle, haystack):
 2     imin, imax = 0, len(haystack)
 3     while True:
 4         if imin >= imax:
 5             return -1
 6         midpoint = (imin + imax) // 2
 7         if haystack[midpoint] > needle:
 8             imax = midpoint
 9         elif haystack[midpoint] < needle:
10             imin = midpoint+1
11         else:
12             return midpoint

Haystack should be sorted in advance. 

以上是关于Binary Search using Python的主要内容,如果未能解决你的问题,请参考以下文章

C++二分查找常用函数

475. Heaters (start binary search, appplication for binary search)

[Leetcode] Binary search tree --Binary Search Tree Iterator

binary search

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

[LeetCode] 173. Binary Search Tree Iterator_Medium_tag: Binary Search Tree