[Leetcode / half] binary search (binary search template title)

A description of the problem:

Is an ordered array, given a number, exists return subscript -1 does not exist;

 

. Twenty-two kinds of recursive comparison:

This question should first thought is recursive implementation.

Two kinds of recursive I mentioned here actually is to achieve an array of segments - one is divided into left and right to open and close the form, and the other is both sides are closed form.

· Right open left closed

int BinarySearch(vector<int> &nums, int l, int r, int target) {
  // 不是你想象地那么完美
  if (l == r) return -1;
  int m = l + (r - l) / 2;        // 防止溢出
  // 建议还是把这个判断放在最前面
  if (target == nums[m]) return m;
  else if (target > nums[m]) return BinarySearch(nums, m + 1, r, target);
  else if (target < nums[m]) return BinarySearch(nums, l, m, target);
}
  1.  Advantages : judgment terminating time particularly convenient, met with two pointers, is over.
  2.  Disadvantage : We left right open and close in fact to a [a, b) interval can live perfectly into [a, c), [c , b) two parts . But here and useless - because I have to dig up the middle element , which looks very discordant.

· Closed all around

int BinarySearch(vector<int> &a, int l, int r, int target) {
  if (l > r) return -1;
  int m = l + (r - l) / 2;        // 防止溢出
  if (target == a[m]) return m;
  else if (target > a[m]) return BS(a, m + 1, r, target);
  else if (target < a[m]) return BS(a, l, m - 1, target);
}

I would like to think before, I found that such an approach is no disadvantage. m + 1 and m - 1 fully reflects the intermediate processing elements dig .

Except to note is that when l == r may have to be processed .

 

III. Non-recursive

Recursive simply outrageous. So we wondered whether the non-recursive implementation .

Then we see a tail recursion, so we do not need to introduce stack. As long as the corresponding circulated.

Implementation is extremely simple, think before you use me here left no defects close right close to achieve.

int BinarySearch(vector<int> &a, int target) {
  // 左闭右也闭的形式
  int l = 0;
  int r = a.size() - 1;
  while (l <= r) {
    int m = l + (r - l) / 2;        // 防止溢出
    if (target == a[m]) return m;
    else if (target > a[m]) l = m + 1;
    else if (target < a[m]) r = m - 1;
  }  
  return -1;
}

 

IV. Other experience

  1. Note to dig up the middle of the element .
  2. Using l + (r - l) / 2 to prevent the overflow of the adder .
Published 137 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43338695/article/details/102765013