***Definition:
A key is a value that you are looking for in
an array.
The simplest type of search is the
sequential
search. In the sequential search, each element of the array is
compared to the key, in the order it appears in the array, until the desired
element is found. If you are looking for an element that is near the front
of the array, the sequential search will find it quickly. The more data
that must be searched, the longer it will take to find the data that matches the
key.
Consider this method which will search for a
key integer value. If found, the index (subscript) of
the first location of the key will be returned. If
not found, a value of -1 will be returned.
public static int
search(int [ ] numbers, int key)
{
for (int index = 0; index < numbers.length; index++)
{
if ( numbers[index] = =
key )
return index;
//We found it!!!
}
// If we get to the end of the
loop, a value has not yet
// been returned. We did not find the key in this
array.
return -1;
} |
If the key value is found,
the index (subscript) of the location is returned.
This tells us that the return value
x, will be the first
integer found such that
numbers [ x ] = key.
There
may be additional key locations in this array
beyond this location. |
|
Now, suppose you are searching for
the number of times
a specific key value is included in an array: |
//Find the number of times the
name "Jones" appears in an array of name
public static void main(String[] args)
{
String key = "Jones";
String[ ] list = new String [100];
// instantiate the array
for ( int i=0; i<100; i++) // fill the array
list [ i ]=Console.readLine("Enter
name: ");
int count = search (list, key);
// invoke the method
System.out.println("Count = " + count);
}
public static int search(String [ ] list, String key) //method to find
"Jones"
{
int i, count = 0;
for( i = 0; i< list.length; i++)
{
if (list [ i ].equals( key ))
count = count+1;
}
return (count);
} |