previous | start

Searching

    1   
    2   import stdlib.*;
    3   import java.util.Arrays;
    4   public class BinarySearch {
    5   
    6     /**
    7      * find the first index in array a where key occurs
    8      * @param key the value to search for in a
    9      * @param a the array 
   10      * @returns the first index in array a where key occurs
   11      * or -1 if key does not occur in array a
   12      */
   13     public static int rank1(int key, int[] a) {
   14       for (int i = 0; i < a.length; i++)
   15         if (a[i] == key) return i;
   16       return -1;
   17     }
   18   
   19     /**
   20      * find the first index in the sorted array a where key occurs;
   21      * this is the same as the number of array elements < key.
   22      * @param key the value to search for in a
   23      * @param a the array; a is required to be sorted!
   24      * @returns the first index in array a where key occurs
   25      * or -1 if key does not occur in array a
   26      */
   27     public static int rank2(int key, int[] a) {
   28       int lo = 0;
   29       int hi = a.length - 1;
   30       while (lo <= hi) {
   31         // key is in a[lo..hi] or not present.
   32         int mid = (lo + hi) / 2;
   33         if (key < a[mid]) {
   34           hi = mid - 1;
   35         } else if (key > a[mid]) {
   36           lo = mid + 1;
   37         } else {
   38           return mid;
   39         }
   40       }
   41       return -1;
   42     }
   43   
   44     /**
   45      * Recursive version of rank2
   46      */
   47     public static int rank3(int key, int[] a) {
   48       return rank (key, a, 0, a.length - 1);
   49     }
   50     public static int rank3(int key, int[] a, int lo, int hi) {
   51       if (lo > hi) {
   52         return -1;
   53       } else {
   54         int mid = (lo + hi) / 2;
   55         if (key < a[mid]) {
   56           return rank3(key, a, lo, mid - 1);
   57         } else if (key > a[mid]) {
   58           return rank3(key, a, mid + 1, hi);
   59         } else {
   60           return mid;
   61         }
   62       }
   63     }
   64   
   65     public static void main(String[] args) {
   66       String fname = "largeW.txt";
   67       StdIn.fromFile ("largeT.txt");
   68           
   69       int[] whitelist = In.readInts(fname);
   70   
   71       Arrays.sort(whitelist);
   72   
   73       // read key; print if not in whitelist
   74       while (!StdIn.isEmpty()) {
   75         int key = StdIn.readInt();
   76         if (rank(key, whitelist) == -1)
   77           StdOut.println(key);
   78       }
   79     }
   80   }


previous | start