fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int upperBound(int[] arr, int target) {
  11. int left = 0;
  12. int right = arr.length;
  13.  
  14. while (left < right) {
  15. int mid = left + (right - left) / 2;
  16.  
  17. if (arr[mid] <= target) {
  18. left = mid + 1;
  19. } else {
  20. right = mid;
  21. }
  22. }
  23.  
  24. return left;
  25. }
  26.  
  27. public static void main(String[] args) {
  28. int[] arr = {1, 3, 5, 6, 6, 7, 7, 9};
  29.  
  30. int target1 = 6;
  31. int index1 = upperBound(arr, target1);
  32. System.out.println("Upper bound of " + target1 + " is at index: " + index1);
  33.  
  34. int target2 = 4;
  35. int index2 = upperBound(arr, target2);
  36. System.out.println("Upper bound of " + target2 + " is at index: " + index2);
  37.  
  38. int target3 = 10;
  39. int index3 = upperBound(arr, target3);
  40. System.out.println("Upper bound of " + target3 + " is at index: " + index3);
  41.  
  42. int target4 = 0;
  43. int index4 = upperBound(arr, target4);
  44. System.out.println("Upper bound of " + target4 + " is at index: " + index4);
  45. }
  46. }
Success #stdin #stdout 0.14s 55516KB
stdin
Standard input is empty
stdout
Upper bound of 6 is at index: 5
Upper bound of 4 is at index: 2
Upper bound of 10 is at index: 8
Upper bound of 0 is at index: 0