fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int upperBound(vector<int> &arr, int x, int n) {
  5. int low = 0, high = n - 1;
  6. int ans = n;
  7.  
  8. while (low <= high) {
  9. int mid = (low + high) / 2;
  10. if (arr[mid] > x) {
  11. ans = mid;
  12. high = mid - 1;
  13. }
  14. else {
  15. low = mid + 1;
  16. }
  17. }
  18. return ans;
  19. }
  20.  
  21. int main()
  22. {
  23. vector<int> arr = {3, 5, 8, 9, 15, 19};
  24. int n = 6, x = 9;
  25. int ind = upperBound(arr, x, n);
  26. cout << "The upper bound is the index: " << ind << "\n";
  27. return 0;
  28. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
The upper bound is the index: 4