Java Reference
In-Depth Information
Searching an Array for a Specific Item
Searching a list for a given item is one of the most common operations performed on a list.
The search algorithm we describe is called the sequential search or linear search. As the
name implies, you search the array sequentially starting from the first array element. You
compare searchItem with the elements in the array (the list) and continue the search until
either you find the item or no more data is left in the list to compare with searchItem .
Consider the list of seven elements shown in Figure 9-10.
[0] [1]
[2] [4] [5] [6]
12 27 18 45 16 38
[3]
[7]
list
35
...
FIGURE 9-10 List of seven elements
Suppose that you want to determine whether 27 is in the list. A sequential search works as
follows: First you compare 27 with list[0] , that is, compare 27 with 35 . Because list[0]
27 , you then compare 27 with list[1] (that is, with 12 , the second item in the list).
Because list[1] 27 , you compare 27 with the next element in the list, that is, compare
27 with list[2] . Because list[2] = 27 , the search stops. This search is successful.
Let's now search for 10 . As before, the search starts at the first element in the list, that is,
at list[0] . Proceeding as before, we see that this time the search item, which is 10 ,is
compared with every item in the list. Eventually, no more data is left in the list to
compare with the search item. This is an unsuccessful search.
It now follows that, as soon as you find an element in the list that is equal to the search item,
you must stop the search and report success. (In this case, you usually also report the location
in the list where the search itemwas found.) Otherwise, after the search item is unsuccessfully
compared with every element in the list, you must stop the search and report failure.
The following method performs a sequential search on a list. To be specific, and for
illustration purposes, we assume that the list elements are of type int .
public static int seqSearch( int [] list, int listLength,
int searchItem)
{
int loc;
boolean found = false ;
loc = 0;
while (loc < listLength && !found)
if (list[loc] == searchItem)
found = true ;
else
loc++;
 
Search WWH ::




Custom Search