fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int upperBound(int arr[], int n, int x) {
  5. int low = 0;
  6. int high = n - 1;
  7. int ans = n; // If no element is greater than x
  8.  
  9. while (low <= high) {
  10. int mid = low + (high - low) / 2;
  11.  
  12. if (arr[mid] > x) {
  13. ans = mid;
  14. high = mid - 1;
  15. }
  16. else {
  17. low = mid + 1;
  18. }
  19. }
  20.  
  21. return ans;
  22. }
  23.  
  24. int main() {
  25. int arr[] = {1, 2, 4, 4, 6, 8, 10};
  26. int n = 7;
  27. int x = 4;
  28.  
  29. cout << "Upper Bound index = " << upperBound(arr, n, x);
  30.  
  31. return 0;
  32. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Upper Bound index = 4