//(see page 244) (from the Carter book)
// This class contains only one method: linear().
// The main() method is in the controlling class,
// called 'FindNum', which calls the linear()
// method here to find an element in the 'array'.
import java.awt.*;
import hsa.Console;
public class Search
{
// returns the index of the element 'numToFind'.
// -1 is returned if the element is not found.
// pre: none
// post: index of numToFind has been returned. -1 has been
// returned if element is not found.
public static int linear (int[] array, int numToFind)
{
int index = 0;
while ((array [index] != numToFind) &&
(index < array.length - 1))
{
index += 1;
} // end of while loop
if (array [index] == numToFind)
{
return (index);
}
else
{
return (-1);
} // end of if-else statement
} // end of linear method
} // end of Search class
No comments:
Post a Comment