Advertisement
Guest User

L50BinarySearch.java

a guest
Mar 23rd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. public class L50BinarySearch{
  2.  
  3.   public static void main(String[] args){
  4.     //ADD CODE HERE TO TEST METHODS
  5.   }
  6.   public static boolean isPalindrome(String s){
  7.     return isPalindrome(s, 0, s.length() - 1);
  8.   }
  9.  
  10.   public static boolean isPalindrome(String s, int low, int high){
  11.     if(high <= low)
  12.       return true;
  13.     else if (!s.substring(low,low+1).equals(s.substring(high,high+1)))
  14.       return false;
  15.     else
  16.       return isPalindrome(s, low+1, high-1);
  17.   }
  18.  
  19.   public static int binarySearch(int a[], int key){
  20.     int lb = 0;
  21.     int ub = a.length - 1;
  22.     while(lb <= ub){
  23.       int m = (lb + ub)/2; //set a midpoint
  24.       if(a[m] == key){
  25.         return m;
  26.       }
  27.       else if (key > a[m]){
  28.         lb = m + 1;   //set a new lowerbound
  29.       }
  30.       else{
  31.         ub = m - 1;   //set a new upper bound
  32.       }
  33.     }
  34.     return -1;     //key not found
  35.   }
  36.  
  37.   private static int binarySearch(int a[], int key, int lb, int ub){
  38.     if(lb > ub){
  39.       return -1; //1. Begin by bailing out
  40.     }
  41.     else{
  42.       int m = (lb + ub)/2;
  43.       if(a[m] == key){
  44.         return m; //2. Process the first
  45.       }
  46.       else if (key > a[m]){
  47.         return binarySearch(a, key, m + 1, ub);  //3. Process
  48.       }        //    the
  49.       else{        //    rest
  50.         return binarySearch(a, key, lb, m - 1);
  51.       }
  52.     }
  53.   }
  54.  
  55.   public static int linearSearch(int[] a, int key){
  56.     for(int i = 0; i < a.length; i++){
  57.       if( a[i] == key ){
  58.         return i;
  59.       }
  60.     }
  61.     return -1;
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement