Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.65 KB | None | 0 0
  1. template<typename T> int BinarySearch(vector<T>& vec, T& request) {
  2.  
  3. T low = 0;
  4. T high = vec.size() - 1;
  5.  
  6. while (low < high) {
  7. T mid = (low / 2 ) + (high / 2); // Styled this way to avoid overflows.
  8. // This looks like where the bug happens, basically low and high both
  9. // become 93 while mid becomes 92,
  10. // it then exits the loop and returns -1 because low is not lower than
  11. // high anymore.
  12. if (vec[mid] == request) {
  13. return mid;
  14. }
  15.  
  16. else if (vec[mid] < request) {
  17. low = mid + 1;
  18. }
  19.  
  20. else if (vec[mid] > request) {
  21. high = mid - 1;
  22. }
  23.  
  24. }
  25. return - 1;
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement