tejasomina

BinarySearch.java

Oct 21st, 2020
568
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class BinarySearch {
  2.     int[] a = new int[]{6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97};
  3.  
  4.     void found(int key, int i) {
  5.         System.out.println(key + " found at index: " + i);
  6.     }
  7.  
  8.     void notFound(int key) {
  9.         System.out.println(key + " not found");
  10.     }
  11.  
  12.     void search(int key, int l, int h) {
  13. //        System.out.println("In search");
  14.         if ((l == h) && a[l] == key) found(key, l);
  15.         else if ((l == h) && a[l] != key) notFound(key);
  16.         else if (a[l] == key) found(key, l);
  17.         else if (a[h] == key) found(key, h);
  18.         else if (l != h) {
  19.             int m = (l + h) / 2;
  20.             if (key == a[m]) found(key, m);
  21.             else if (key < a[m]) search(key, l, m - 1);
  22.             else if (key > a[m]) search(key, m + 1, h);
  23.         }
  24.     }
  25.  
  26.     public static void main(String[] args) {
  27.         BinarySearch bs = new BinarySearch();
  28.         bs.search(6, 0, bs.a.length - 1);
  29.         bs.search(97, 0, bs.a.length - 1);
  30.         bs.search(53, 0, bs.a.length - 1);
  31.         bs.search(33, 0, bs.a.length - 1);
  32.         bs.search(34, 0, bs.a.length - 1);
  33.         bs.search(51, 0, bs.a.length - 1);
  34.     }
  35. }
  36.  
RAW Paste Data