binary search

Posted

tags:

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

The implementation of binary search is not complicated, but it is a vivid illustration of the power of divide-and-conquer.

Here is the code

 1 int binarySearch(int a[], int n, int x){
 2     int lo = 0;
 3     int hi = n-1;
 4     while(lo<=hi){
 5         int mid = lo + (hi-lo)/2;
 6         if (a[mid] == x) return mid;
 7         else if(a[mid]<x)
 8             lo = mid + 1;
 9         else hi = mid - 1;
10     }
11     return -1;  //not found;
12 }

Pay attention to line 5: we can‘t use ‘mid = (lo+hi)/2‘ here. we may have over-flow if (lo+hi)>231 - 1.

More details about this subtle bug.

 

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

Complete Binary Search Tree

Validate binary search tree

PAT1064: Compelte Binary Search Tree

PAT1099:Build A Binary Search Tree

[LeetCode]题解(python):099-Recover Binary Search Tree

[LeetCode]题解(python):096-Unique Binary Search Trees