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.
  • looking through data to find everyone that has bought something from you in the last month
  • searching through data to find out if a particular username and password are valid
  • finding a particular URL by using an online search engine
  • finding a book in the library
  •  

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
{

JLabel enterLabel, resultLabel;
JTextField enter, result;
int a[];

public void init( )
{

// setting up the GUI
Container c = getContentPane();
c.setLayout(new FlowLayout());

enterLabel = new JLabel("Enter integer between 1 and 100 to search for");
c.add(enterLabel);

// Here we add the actionListener to the JTextField
// so that the code will execute when the user enters
// a number ion the text field and hits enter

enter = new JTextField(10);
enter.addActionListener(this);
c.add(enter);

resultLabel = new JLabel("Found value at array element ");
c.add(resultLabel);

result = new JTextField(10);
result.setEditable(false);
c.add(result);

// create an array and populate it with 100 random integers
// it is not necessarily the case that all of the numbers
// from 1 to 100 will be in the array
// there may be some repeats

a = new int[100];

for (int i = 0; i < a.length; i++)

a[i] = 1 + (int) (Math.random() * 100);

}

// Search the array for the specified cell that contains it
// this Linear Search will only find the first occurrence of a number

public int linearSearch(int array[], int key)
{

for (int n = 0; n < a.length; n++)

if ( array[n] == key )

// if key is found then return
// the index in the array where it was found

return n;

// if not found return -1
return -1;

}

public void actionPerformed(ActionEvent e)
{

String searchKey = e.getActionCommand();

//  invoke the LinearSearch method with appropriate inputs
int element = linearSearch( a, Integer.parseInt( searchKey));

//  what is written to the text field depends on whether something was found
if (element != -1)

result.setText(Integer.toString(element));

else

result.setText("Value not found");

}

}

 

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.

  • import java.awt.*
  • import java.awt.event.*
  • import javax.swing.*
  • declare the overall inclusive class LinearSearch
    • extending JApplet
    • implementing ActionListener
  • declare two JLabels for describing text fields
  • declare two JTextFields
    • one for entering the number to search for
    • the other to display whether and where it was found in the array
  • declare and array of integers called a[ ]

     

  • declare method init( )
    • declare a container to be the content pane of the applet
    • set the layout for the container to be a FlowLayout( )
    • instantiate/construct a JLabel to identify entry text field
    • add the JLabel to the container
    • instantiate/construct a JTextField for input entry
    • add an actionListener so that the program will respond to the user entering a number and hitting the enter key
    • add the JTextField to the container
    • instantiate/construct a JLabel to identify the results text field
    • add the JLabel to the container
    • instantiate/construct a JTextField for display of results
    • add the JTextField to the container
    • use a for loop to fill the array a[ ] with randomly generated integers from 1 to 100
      • a[i] = 1 + (int) (Math.random( ) * 100)
  • end the method init( )

 

  • declare method LinearSearch( )
    • returns an integer
    • requires the array of random numbers be passed to it
    • uses a for loop to go through the entire array until the desired value is found
      • if found
        • returns index of the of the element that contains it in the array
      • if not found
        • returns -1
  • end the method LinearSearch( )

 

 

  • declare method actionPerformed( )
    • gets the entry from the text field and calls it searchKey
    • invokes the LinearSearch( ) method
      • passes the array of randomly generated integers from 1 to 100
      • passes the searchKey
    • if searchKey is found
      • displays index of element in array where first occurrence of searchKey is located in result JTextField
    • if searchKey not found
      • displays "Value not ofund" in result JTextField

 

You can play with this all you want.