fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int binarySearch(vector<int> a, int low, int high, int x)
  5. {
  6. while (low <= high) {
  7. int mid = low + (high - low) / 2;
  8. if (a[mid] == x)
  9. return mid;
  10. if (a[mid] < x)
  11. low = mid + 1;
  12. else
  13. high = mid - 1;
  14. }
  15. return -1;
  16. }
  17.  
  18. int main()
  19. {
  20. int n; cin >> n;
  21. vector<int> a(n);
  22. for(int i=0; i<n; i++){
  23. cin >> a[i];
  24. }
  25. cout << binarySearch(a, 0, n-1, 5);
  26. }
  27.  
Success #stdin #stdout 0.01s 5288KB
stdin
5
1 2 3 4 5
stdout
4