20-CS-4003-001 Organization of Programming Languages Fall 2017
Actual Programs

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures

Binary Search

Java:
   
   import java.io.*;

   class BinSearch {
      int elem[], nelem;

      public int binsearch (int low, int high, int x) {
         while (low <= high) {
            int mid = (low+high)/2;
            if (x == elem[mid]) return mid;
            if (x < elem[mid]) high = (low+high)/2-1;
            else low = (low+high)/2+1;
         }
         return -1;
      }

      public BinSearch (int n) {
         nelem = n;
         elem = new int[n];
         elem[0] = 23;
         for (int i=1 ; i < n ; i++) 
            elem[i] = elem[i-1] + (int)(20*Math.random());
      }

      public void show () {
         for (int i=0 ; i < nelem ; i++) System.out.print(elem[i]+" ");
         System.out.println();
      }

      public int binsearch (int x) {  return binsearch(0, nelem-1, x);  }
   }

   public class intro_6 {
      public static void main (String args[]) {
         try {
            int finder;
            BinSearch bs = new BinSearch(Integer.parseInt(args[0]));
            bs.show();
            System.out.print("Find: ");
            BufferedReader br = 
               new BufferedReader(new InputStreamReader(System.in));
            finder = Integer.parseInt(br.readLine());
            System.out.println("Result: index=" +bs.binsearch(finder));
         } catch (Exception e) {
            System.out.println("Usage: java intro_6 ");
         }
      }
   }

The above can be run as follows:

   prompt> java intro_6 20
   23 27 33 33 47 56 64 72 72 77 88 104 115 121 133 136 138 154 165 172
   Find: 121
   Result: index=13
 
Haskell:
bs :: (Ord a) => a -> [a] -> Int -> Int -> Int
bs x lst low high = pp
  where
     mid = (div (high+low) 2)
     pp = if low > high then
             -1
          else if x == (lst !! mid) then
             mid
          else if x < (lst !! mid) then
             bs x lst low (mid-1)
          else
             bs x lst (mid+1) high
The signature shown at the top of the code was taken from the types inferred by the Haskell interpreter. This example shows direct recursion in Haskell and the use of an if-then-else construct. Run it, for example, like this:
   ghci> bs 6 [1,2,3,4,5,6,7,8,9] 0 8
   5
 
Scheme:
(define bs 
   (lambda (x lst low high)
      (let ((mid (floor (/ (+ high low) 2))))
         (if (< high low)
             -1
             (if (= x (list-ref lst mid))
                 mid
                 (if (< x (list-ref lst mid))
                     (bs x lst low (- mid 1))
                     (bs x lst (+ mid 1) high)))))))

Run it like this:

   scheme> (bs 6 '(1 2 3 4 5 6 7 8 9) 0 8)
   ;Value: 5