Advertisement
Zeill

Binary Search

Oct 22nd, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. public class BusquedaBinaria {
  2.    
  3.      // Returns index of x if it is present in arr[l..
  4.     // r], else return -1
  5.     int binarySearch(int arr[], int l, int r, int x)
  6.     {
  7.         if (r >= l) {
  8.             int mid = l + (r - l) / 2;
  9.  
  10.             // If the element is present at the
  11.             // middle itself
  12.             if (arr[mid] == x)
  13.                 return mid;
  14.  
  15.             // If element is smaller than mid, then
  16.             // it can only be present in left subarray
  17.             if (arr[mid] > x)
  18.                 return binarySearch(arr, l, mid - 1, x);
  19.  
  20.             // Else the element can only be present
  21.             // in right subarray
  22.             return binarySearch(arr, mid + 1, r, x);
  23.         }
  24.  
  25.         // We reach here when element is not present
  26.         // in array
  27.         return -1;
  28.     }
  29.  
  30.     // Metodo Main
  31.     public static void main(String args[])
  32.     {
  33.         BusquedaBinaria ob = new BusquedaBinaria();
  34.         int arr[] = { 2, 3, 4, 10, 40, 75, 103 };
  35.         int n = arr.length;
  36.         int x = 10;
  37.         int result = ob.binarySearch(arr, 0, n - 1, x);
  38.         if (result == -1)
  39.             System.out.println("[-1] No se encuentra el elemento");
  40.         else
  41.             System.out.println("Elemento encontrado en el índice: " + result);
  42.     }
  43.    
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement