Tuesday, March 25, 2014

Binary Chop in Java

class BinChop
{
  public interface Strategy
  {
    public int chop(final int a[], int sz, int value);
  }; 
 
  public class Chopper implements Strategy
  {
    public int chop (final int a[], int sz, int value)
    {
      int first = 0;
      int last  = sz;
     
      while (first <= last)
      {
        int mid = (first + last)/2;  // <== potential overflow
       
        if (value < a[mid])
          last = mid - 1;
        else if (value > a[mid])
          first = mid + 1;
        else
          return mid;
      }
      return -1;
    }
  }   
 
  public class ChopperOverflow implements Strategy
  {
    public int chop (final int arr[], int n, int key)
    {
      int min = 0, max = n;
      while (min < max) {
        int middle = min + ((max - min) >> 1);  // overflow fixedmin + ((max - min) >> 1)
        if (key > arr [middle])
          min = middle + 1;
        else
          max = middle;
      }
      if (arr[min] == key) return min;
      else
        return -1;
    }
  }
 
  public static void main(String args[])
  {
    int a[] = {3, 4, 5, 10, 20, 21, 25, 29, 31, 35};
   
    Strategy strat = new BinChop().new Chopper();
    System.out.println(strat.chop(a, 10, 20));
   
    strat = new BinChop().new ChopperOverflow();
    System.out.println(strat.chop(a, 10, 20));
  } 
}

No comments:

Post a Comment