Searching for an Element in an Array
Introduction.
There are some fairly classic problems in Computer Science that are
fundamental and must be solved before getting to other problems.
Searching through data is one of the
most fundamental. It is possible to think of plenty of applications
of searching such as the following.
Obviously, these sorts of scenarios are endless. So, you should be able to see that quickly and efficiently being able to find the desired information is very important. If it takes too long then it delays all kinds of other things that may be more important. As usual, the pure algorithmic aspects of searching belie the difficulty of many other issues concomitant with searching such as what criteria should be used for searching. But we will look past these other issues and focus on a highly structured situation where we have an array of data of a particular data type in which we want to find something. This next applet will randomly generate an array of size 100 of integers from 1 to 100. Thus you do not know where a particular number is located or if such a number actually got generated. But this will serve the purpose of illustrating some coding approaches that many consider to be worth knowing about. This applet is a modification of one of the same name in Deitel and Deitel. It should be called LinearSearch.java. |
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LinearSearch extends JApplet implements ActionListener {
} |
Notice, we have done a fairly minimal implementation with no error trapping and a flow layout. Since the size of the applet window impacts the display it is given below in LinearSearch.html. |
<html> <applet code="LinearSearch.class" width=400 height=100> </applet> </html> |
I ran the program with the following input. Your
results will almost surely differ due to the random number generation.
But there should be some overall similarities. Remember, you only need to enter an integer in the text field and hit enter to get the code to execute. |
I then tried some different input values until I came up with an integer that didn't get generated. |
Code Discussion. We will use our usual outline form to discuss the code.
You can play with this all you want. |