fork download
  1. public class Main {
  2. public static int upperBound(int[] arr, int target) {
  3. int left = 0;
  4. int right = arr.length;
  5.  
  6. while (left < right) {
  7. int mid = left + (right - left) / 2;
  8.  
  9. if (arr[mid] <= target) {
  10. left = mid + 1;
  11. } else {
  12. right = mid;
  13. }
  14. }
  15.  
  16. return left;
  17. }
  18.  
  19. public static void main(String[] args) {
  20. int[] arr = {1, 3, 5, 6 , 6, 7, 7, 9};
  21. int target = 6;
  22. int upperBoundIndex = upperBound(arr, target);
  23.  
  24. if (upperBoundIndex < arr.length) {
  25. System.out.println("Upper bound of " + target + " is at index " + upperBoundIndex);
  26. } else {
  27. System.out.println("Upper bound of " + target + " is not found in the array. n = " + arr.length);
  28. }
  29. }
  30. }
  31.  
Success #stdin #stdout 0.13s 57592KB
stdin
Standard input is empty
stdout
Upper bound of 6 is at index 5