Page 424 - Introduction to Programming with Java: A Problem Solving Approach
P. 424
390 Chapter 10 Arrays and ArrayLists
/********************************************************************
*
CourseDriver.java
Dean & Dean
This class creates a Course object and searches for a student
id within the newly created Course object.
********************************************************************/
*
*
*
*
import java.util.Scanner;
public class CourseDriver
{
}
// end class CourseDriver
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
int[] ids = {4142, 3001, 6020};
Course course = new Course("CS101", ids, ids.length);
int id;
int index;
// ID being searched for
// index of ID sought or -1 if not found
System.out.print("Enter 4-digit ID: ");
id = stdIn.nextInt();
Apago PDF Enhancer
index = course.findStudent(id);
if (index >= 0)
{
}
else
{
}
Sample session:
System.out.println("found at index " + index);
System.out.println("not found");
Enter 4-digit ID: 3001
found at index 1
Figure 10.11 Driver for program illustrating a sequential search Binary Search
If you have an array with a large number of array elements, like 100,000, a sequential search typically takes quite a long time. If such an array has to be searched many times, it’s often worthwhile to use a binary search. Binary search gets its name from the way that it bisects a list of values and narrows its search to just half of the bisected list.
For a binary search to work on an array, the array must be sorted so that everything is in some kind of alphabetical or numerical order. The next section describes one of the many available sorting methods. This initial sorting takes more time than a single sequential search, but you have to do it only once.