CSCI 120 Lab 6


Objectives

In this focussed lab you will gain some experience in coding with an array of objects encapsulated in a class, by implementing binary search (on an array) in such a class.

Activities

  1. Download PhoneBook.java, PhoneBookRecord.java and PhoneOperator.java and create a project.
  2. Play with it a little bit (the driver class is, of course, PhoneOperator) to familiarize yourself with how it works.
  3. Before we launch into binary search, we must make sure the array is sorted. Happily, selection sort has been built into the class definition. Do an appropriate method invocation to ensure that the array is sorted before it's printed out in PhoneOperator. Enter some names once again, and check that they are sorted (alphabetically according to hame).
  4. Take a good look at the lookUp() method. Note how it loops through the array and compares the key ("aName") to each array element. If it's equal, it breaks out of the loop and returns the number at that same index, otherwise it returns "Unlisted number". The way it determines if the name is found is perhaps a little overly slick; it simply realizes that if the index is less than the number in the book, the name has been found. We also could have used a boolean variable "found". And that way of doing things makes it easier to implement binary search.
  5. Write a new version of lookUp(), called binaryLookUp(). It should have the same parameters and return type as lookUp(), but it will use binary search. In case you have forgotten, here's some pseudocode:
      left = the leftmost index;
      right = the rightmost index; //Of the portion of the array that is *used*
      found = false;
      while (left <= right && found is false)
      {
          find the middle between left and right;
          if (the key equals the name in the middle)
            set found to true;
          else if (the key is less than the name in the middle)
            adjust right so that it's just to the left of the middle
          elsea
            adjust left so that it's just to the right of the middle;
      }
      
      if (found)
        return the number at the middle;
      else
        return "Unlisted number";
     }
    
    Implement this pseudocode in binaryLookUp(), and change the lookUp() method invocation in PhoneOperator so that it's binaryLookUP(). Many hints for how to do this can already be found in the original lookUp() method (which I hope you don't delete).
  6. Test that it works for several names.
  7. Submit electronically and, time permitting, begin work on assignment 8


Back to CS 120 Home Page