Answer:

No... but you should know that binary search exists in case you need it in a large application. With large amounts of data, binary search is very much faster than linear search.

Tiny Dictionary

The following program implements a tiny dictionary. The user enters a word, the program looks up the word and prints the word and its definition. With a little work, this program could be turned into an almost practical application.

class TinyDictionary
{
  
  public static void main ( String[] args )
  {
    Entry[] wordList = new Entry[10];
    
    wordList[0] = new Entry( "WWW", "World Wide Web" );
    wordList[1] = new Entry( "HTTP","Hypertext Transport Protocol" );
    wordList[2] = new Entry( "DNS", "Domain Name System" );
    wordList[3] = new Entry( "AWT", "Application Windowing Toolkit" );
    wordList[4] = new Entry( "CPU", "Central Processing Unit" );
    wordList[5] = new Entry( "RAM", "Random Access Memory" );
    wordList[6] = new Entry( "URL", "Uniform Resource Locator" );
    wordList[7] = new Entry( "GUI", "Graphical User Interface" );
    wordList[8] = new Entry( "API", "Application Programming Interface" );
    wordList[9] = new Entry( "ROM", "Read-only Memory" );
    
    Arrays.sort( wordList );
    
    Scanner scan = new Scanner( System.in );
    String key = "";
    int location;

    System.out.print("Word: ");
    key = scan.next();
    
    while ( !key.equals("quit") && !key.equals("q") )
    {      
      location = Arrays.binarySearch( wordList, new Entry( key, "" ) );
      
      if ( location < 0 )
        System.out.println("Not in the dictionary");
      else
        System.out.println( wordList[location]  );

      System.out.print("Word: ");
      key = scan.next();
    }
    
  }  

}

The binary search method is a static method of the Arrays class, so it can be invoked by Arrays.binarySearch() without the need for an Arrays object.

The parameters are a sorted list of Entry objects, and an Entry object to serve as the key to look up. The key is constructed using the word the user entered and an empty string for the definition:

new Entry( key, "" )

Since the compareTo() method does not look at the definition, this works fine. Here is sample output from the program:

Word: URL
URL     Uniform Resource Locator
Word: WWW
WWW     World Wide Web
Word: quit

QUESTION 18:

Must all the cells of the array be non-null to use Arrays.binarySearch()?