***Definition:
A key is a value that you are looking for in
an array.
The simplest type of search is the sequential
search (or linear 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 end of loop, a value has not yet
// been returned. The key in not 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 names
public static void main(String[] args)
{
Scanner reply= new Scanner(System.in);
String key = "Jones"; //case sensitive - "Jones" will not equal "jones"
String[ ] list = new String [100]; // instantiate the array
for ( int i=0; i<100; i++) // fill the array from the keyboard
{
System.out.println("Enter name: ");
list [ i ]=reply.nextLine( );
}
int count = search (list, key); // invoke the method
System.out.println("Count = " + count);
reply.close();
}
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);
} |