Search code examples
c++algorithmbinary-search

Implement binary search


This is my binary-search:

int binarySearch(int arr[], int value, int min, int max){
  int pos = -1;

  while (max >= min && pos == -1) {
    int mid = (max+min)/2;

    if(arr[mid] ==  value){
      pos = mid;
    }else if(arr[mid] < value){
      min = mid +1;
    }else if(arr[mid] > value){
      max = mid -1;
    }

  }
  return pos;
}

I call it this way:

 //Arr contain values 0-63
int i = binarySearch(arr, 64, 0, 64);

These are the mid values

32 48 56 60 62 63 64

At the last check I try to access an element at pos 64, when the last position in the array is 63.

What's wrong with my implementation?


Solution

  • Your Array contains values from 0-63 (as you mentioned) and you are giving following values for min and max: min=0, max=64. And change the following line so that your code can handle high int values otherwise there are chances of memory overflow.

           int mid = min+(max-min)/2;
    

    The above formula simplifies to (max+min)/2 itself but protect integer overflow.