fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int BinarySearch(vector<int> arr, int key)
  4. {
  5. int start =0, end = arr.size()-1;
  6. while(start<=end)
  7. {
  8. int mid = start + (end-start)/2;
  9.  
  10. if(arr[mid]==key)
  11. {
  12. return mid;
  13. }
  14. else if(key<arr[mid])
  15. {
  16. end = mid-1;
  17. }
  18. else
  19. {
  20. start = mid+1;
  21. }
  22. }
  23. return -1;
  24. }
  25. int main() {
  26. // your code goes here
  27. vector<int> arr = {1,3,4,6,7,8};
  28.  
  29. cout<<BinarySearch(arr,8)<<endl;
  30.  
  31. return 0;
  32. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
5