Mahmoud_Hawara

Binary Search

Jan 10th, 2023
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1.  
  2. public class Solver
  3. {
  4.     public static void main(String args[])
  5.     {
  6.        
  7.     }
  8.  
  9.     public static boolean binary_serach(int a[], int l, int r, int target)
  10.     {
  11.         if (l > r)return false;
  12.         if (l == r)return a[l] == target;
  13.         int mid = (l + r) >> 1;
  14.         if (target == a[mid])return true;
  15.         if (a[mid] > target)return binary_serach(a, l, mid - 1, target);
  16.         else return binary_serach(a, mid + 1, r, target);
  17.     }
  18.  
  19.     public static int lower_bound(int a[], int l, int r, int target)
  20.     {
  21.         if (l > r)return -1;
  22.         if (l == r)
  23.         {
  24.             if (a[l] >= target)return a[l];
  25.             return -1;
  26.         }
  27.         int mid = (l + r) >> 1;
  28.         if (a[mid] >= target)return lower_bound(a, l, mid, target);
  29.         else return lower_bound(a, mid + 1, r, target);
  30.     }
  31.  
  32.     public static int upper_bound(int a[], int l, int r, int target)
  33.     {
  34.         if (l > r)return -1;
  35.         if (l == r)
  36.         {
  37.             if (a[l] > target)return a[l];
  38.             return -1;
  39.         }
  40.         int mid = (l + r) >> 1;
  41.         if (a[mid] > target)return upper_bound(a, l, mid, target);
  42.         else return upper_bound(a, mid + 1, r, target);
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment