fork download
  1. public class Main {
  2.  
  3. public static int ub(int[] a, int x) {
  4. int lo = 0;
  5. int hi = a.length - 1;
  6.  
  7. while (lo <= hi) {
  8. int mid = (lo + hi) / 2;
  9. if (a[mid] <= x) {
  10. lo = mid + 1;
  11. } else {
  12. if (mid == 0) return 0;
  13. if (a[mid - 1] <= x) return mid;
  14. hi = mid - 1;
  15. }
  16. }
  17. return lo;
  18. }
  19.  
  20. public static void main(String[] args) {
  21. int[] data = {2, 4, 4, 4, 8, 12, 12, 15};
  22. int find = 4;
  23. int pos = ub(data, find);
  24.  
  25. if (pos < data.length) {
  26. System.out.println("Upper bound position: " + pos);
  27. } else {
  28. System.out.println("Upper bound position: " + data.length);
  29. }
  30. }
  31. }
  32.  
Success #stdin #stdout 0.12s 53588KB
stdin
Standard input is empty
stdout
Upper bound position: 4