This class is designed to test the efficiency of the two search models.

You will simultaneously populate both arrays with the same random numbers. This will guarantee that both arrays have the exact same content. Sort only ONE array using Arrays.sort. This sorted array will be used with the bin_search method and the unsorted array will be used with seq_search.

Write code to read integers from System.in until EOF. With each integer search each array using seq_search and bin_search. Report the number of elements examined for each search method, whether or not the item was found and where in the array you found it.

The number of array elements examined is stored in static instance variables. These variables for sequential and binary search are SEQ_NUM and BIN_NUM respectively. The appropriate variable is set when the corresponding search method is called.

public class P10Class
{
  public static int SEQ_NUM;
  public static int BIN_NUM;

  public static int seq_search(int[] data, int key)
  {
    boolean found = false;
    int i = 0;

    SEQ_NUM = 0;

    while ( !found && (i < data.length) )
    {
      if ( data[i] == key )
        found = true;
      else
        i++;

      SEQ_NUM++;
    }

    if ( found )
      return i;
    else
      return -1;
  }

  public static int bin_search(int[] data, int key)
  {
    boolean found = false;
    int midpoint = 0, first = 0, last;

    BIN_NUM = 0;
    last = data.length - 1;

    while ( ( first <= last ) && !found )
    {
      midpoint = (first + last) / 2;
      if ( data[midpoint] == key )
        found = true;
      else if ( data[midpoint] > key )
        last = midpoint - 1;
      else
        first = midpoint + 1;

      BIN_NUM++;
    }

    if ( found )
      return midpoint;
    else
      return -1;
  }
}

Recommended Answers

All 4 Replies

You must explain what help you need.

I dont know how to do the secondpart of it the part that is up there in the description i got this part done

You didn't even finish the first part yet! The requirement said you need 2 arrays, not one. Then, you need to randomly select a value and put the value into both array at the same time.

Your search is looking inside only 1 array. The bin search should be looking in the sorted array and the seq search should be looking in the pre-sorted array...

thats what i need help with i got confused

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.