CH12 – Binary Search

  1. Complete the previous exercises in this chapter if you haven’t done so already.
  2. Open CardDriverTwo.java and add the following method.
public static int binarySearch(Card[] cards, Card target){
  int low = 0;
  int high = cards.length - 1;
  while (low <= high){
    int mid = (low + high)/2;
    int comp = cards[mid].compareTo(target);
    if(comp == 0){
      return mid;
    }
    else if (comp < 0) {
      low = mid + 1;
    }
    else {
      high = mid - 1;
    }
  }
  return -1;
}
  1. Modify main so that it calls binarySearch rather than search.
int location = binarySearch(cards, theCard);
  1. Compile and run the program.
$ javac CardDriverTwo.java
$ java CardDriverTwo 5 1
Ace of Clubs
King of Spades
5 of Diamonds
5 of Diamonds
$ java CardDriverTwo 4 3
Ace of Clubs
King of Spades
4 of Spades
4 of Spades