CIS 180: Object-Oriented Programming

Laboratory Exercise #12

In this lab you will implement the binary search algorithm discussed in class. The application you complete will display a sorted array of 500 random integers in a scrolling list. There is a text box to enter a number to search for, a "Search" button and a "Reload" button. When the search button is clicked, the application should highlite the correct number if it is in the list, otherwise highlite "Not Found". The reload button causes a new set of numbers to be loaded into the array and displayed in the list.

Exercises

  1. The only method that you need to complete is the search method in the BinarySearchAlgorithm class. It takes a sorted array of integers and a target to search for as parameters. The precise behavior of the method is defined in comments in the starting code as preconditions and postconditions.

Hints

Think carefully about how you calculate the middle element of the range you are searching. It is not difficult, but most students get this wrong at first. Also, remember that as you search you must narrow the range of the search on every iteration of the loop. Think carefully about what happens when the range you are searching contains only one or two elements. (If there is only one element left the highest, lowest, and middle elements will all be the same. When there are two elements left the middle will be the same as either the highest or lowest.) However, you should be able to write a correct implementation without checking for any special cases.