Question

I have the following classes SearchMain.java import java.security.SecureRandom; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** *...

I have the following classes

SearchMain.java

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
*
* DO NOT CHANGE THIS CODE
*
*/
public class SearchMain {
   public static void main(String[] args) {
       ArraySearcher arraySearch = new ArraySearchImp();
       SecureRandom secureRandom = new SecureRandom();
       int[] sortedArray = generateRandomSortedIntArray(10);
       System.out.println(Arrays.toString(sortedArray));
       Set<Integer> intSet = new HashSet<Integer>();
      
       for(int i = 0; i < 5; i++) {
           int randomInt;
           do {
               randomInt = sortedArray[secureRandom.nextInt(sortedArray.length-1)+1];
           } while(intSet.contains(randomInt));
          
           intSet.add(randomInt);
           testSearchMethods(arraySearch, sortedArray, randomInt);
       }
      
       testSearchMethods(arraySearch, sortedArray, sortedArray[0]);
       testSearchMethods(arraySearch, sortedArray, sortedArray[sortedArray.length-1]);
       testSearchMethods(arraySearch, sortedArray, sortedArray[sortedArray.length-1] + 1);
       testSearchMethods(arraySearch, sortedArray, sortedArray[0] -1);
       testSearchMethods(arraySearch, sortedArray, -10);
   }
  
   private static void testSearchMethods(ArraySearcher arraySearch, int[] sortedArray, int valueToSearchFor) {
       int result = Arrays.binarySearch(sortedArray, valueToSearchFor);
       result = result < 0 ? -1 : result;
      
       System.out.println("\nValue to search for: "+ valueToSearchFor + "; expected result: " + result);
      
       System.out.print("Linear search...");
       int linearSearchResult                = arraySearch.linearSearch(sortedArray, valueToSearchFor);
       if(result == linearSearchResult) {
           System.out.println("[OK]");
       } else {
           System.out.println("[ X ] - index returned: " + linearSearchResult);
       }
      
       System.out.print("Binary search...");
       int binarySearchResult                = arraySearch.binarySearch(sortedArray, valueToSearchFor);
       if(result == binarySearchResult) {
           System.out.println("[OK]");
       } else {
           System.out.println("[ X ] - index returned: " + binarySearchResult);
       }
      
       System.out.print("Binary search...");
       int binarySearchRecursiveResult    = arraySearch.binarySearchRecursive(sortedArray, valueToSearchFor);
       if(result == binarySearchRecursiveResult) {
           System.out.println("[OK]");
       } else {
           System.out.println("[ X ] - index returned: " + binarySearchRecursiveResult);
       }
   }
  
   private static int[] generateRandomSortedIntArray(int arraySize) {
       SecureRandom secureRandom = new SecureRandom();
      
       int[] array = new int[arraySize];
       int previousInt = 0;
      
       for(int i = 0; i < array.length; i++) {
           int randomInt = secureRandom.nextInt(10) + 1;
           array[i] = previousInt + randomInt;
           previousInt = array[i];
       }
      
       return array;
   }
}

----------------------------------------------

ArraySearcher.java

/**
*
* DO NOT CHANGE THIS CODE
*
*/
public interface ArraySearcher {
   /**
   *
   * Also known as sequential search
   *
   * @param array               - an int[] array
   * @param valueToSearchFor   - the value to search for
   * @return index of <valueToSearchFor> if found in <sortedArray>, -1 otherwise
   */
   public int linearSearch(int[] array, int valueToSearchFor);
  
   /**
   *
   * The non-recursive version of binarySearch
   *
   * @param sortedArray       - the array must be sorted
   * @param valueToSearchFor   - the value to search for
   * @return index of <valueToSearchFor> if found in <sortedArray>, -1 otherwise
   */
   public int binarySearch(int[] sortedArray, int valueToSearchFor);
  
   /**
   *
   * The recursive version of binarySearch
   *
   * @param sortedArray       - the array must be sorted
   * @param valueToSearchFor   - the value to search for
   * @return index of <valueToSearchFor> if found in <sortedArray>, -1 otherwise
   */
   public int binarySearchRecursive(int[] sortedArray, int valueToSearchFor);
}

---------------------------------------

I need to create

ArraySearchImp.java

to output the following

----------------------------------

------------- A sample run of SearchMain.java which shows correct implementation ---------

[4, 12, 20, 23, 31, 33, 43, 44, 45, 48]

Value to search for: 33; expected result: 5 Linear search.................. [OK]

Binary search.. [OK]

Binary search.. [OK]

Value to search for: 45; expected result: 8 Linear search.................. [OK]

Binary search.. [OK]

Binary search.. [OK]

Value to search for: 23; expected result: 3 Linear search.................. [OK]

Binary search.. [OK]

Binary search.. [OK]

Value to search for: 44; expected result: 7 Linear search.................. [OK]

Binary search.. [OK]

Binary search.. [OK]

Value to search for: 48; expected result: 9 Linear search.................. [OK]

Binary search.. [OK]

Binary search.. [OK]

Value to search for: 4; expected result: 0 Linear search...[OK]

Binary search...[OK] Binary search...[OK]

Value to search for: 48; expected result: 9 Linear search...[OK]

Binary search...[OK] Binary search...[OK]

Value to search for: 49; expected result: -1 Linear search...[OK]

Binary search...[OK] Binary search...[OK]

Value to search for: 3; expected result: -1 Linear search...[OK]

Binary search...[OK] Binary search...[OK]

Value to search for: -10; expected result: -1 Linear search...[OK]

Binary search...[OK] Binary search...[OK]

-----------------------------------------------------------------

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the code in JAVA for the above question:

(ArraySearchImp.java)

//class ArraySearchImp that implements ArraySearcher.
public class ArraySearchImp implements ArraySearcher {
   //method linear Search.
   @Override
   public int linearSearch(int[] array, int valueToSearchFor) {
       // TODO Auto-generated method stub
       //length of array.
       int n = array.length;
      
       //searching value using linear search
       for (int i = 0; i < n; i++) {
           //if value at i in array is equal to valueToSearchFor
           if (array[i] == valueToSearchFor)
               //returning index if found.
               return i;
       }
       //returning -1 if not found.
       return -1;
   }
  
   //iterative binary search method.
   @Override
   public int binarySearch(int[] sortedArray, int valueToSearchFor) {
       // TODO Auto-generated method stub
      
       int left = 0, right = sortedArray.length - 1;
      
       //iterating till left is less than or equal to right.
       while (left <= right) {
           //finding mid index of sortedArray
           int mid = (left + right) / 2;
          
           //if element at index mid is equal to valueToSearchFor
           if (sortedArray[mid] == valueToSearchFor)
               return mid;
          
           //if element at index mid is less than valueToSearchFor
           if (sortedArray[mid] < valueToSearchFor)
               left = mid + 1;
           else
               right = mid - 1;
       }
       //returning -1 if not found.
       return -1;
   }

   @Override
   public int binarySearchRecursive(int[] sortedArray, int valueToSearchFor) {
       // TODO Auto-generated method stub
       //finding index using helper method of binarySearchRecursive.
       int find = binarySearchRecursiveHelper(sortedArray, valueToSearchFor, 0, sortedArray.length - 1);
       //returning index of the element which is stored in variable find.
       return find;
   }
  
   //helper function to find element using binary search recursively.
   public int binarySearchRecursiveHelper(int[] sortedArray, int valueToSearchFor, int left, int right) {

       if (right >= left) {
           int mid = (left + right) / 2;
          
           //if value at index mid is equal to valueToSearchFor
           if (sortedArray[mid] == valueToSearchFor)
               return mid;
           //if value at index mid is greater than valueToSearchFor
           if (sortedArray[mid] > valueToSearchFor)
               return binarySearchRecursiveHelper(sortedArray, valueToSearchFor, left, mid - 1);
          
           //if value at index mid is less than valueToSearchFor
           if (sortedArray[mid] < valueToSearchFor)
               return binarySearchRecursiveHelper(sortedArray, valueToSearchFor, mid + 1, right);
       }
       //returns -1 if not found.
       return -1;
   }
}

Refer to the screenshot attached below to better understand the code and indentation:

(ArraySearchImp.java)




Output:



If this answer helps you then please upvote,
for further queries comment below.


Thank you.

Add a comment
Know the answer?
Add Answer to:
I have the following classes SearchMain.java import java.security.SecureRandom; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** *...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • Need help with this Java project implementing an interpolation search, bolded the missing parts: /**   ...

    Need help with this Java project implementing an interpolation search, bolded the missing parts: /**    A class that implements an interpolation search and    a binary search of a sorted array of integers.    @author Frank M. Carrano    @author Timothy M. Henry    @version 4.0 */ public class SearchComparer {    private int[] a;    private int interpolationSearchCounter;    private int binarySearchCounter;    private static final int CAPACITY = 50;    public SearchComparer(int[] array, int n)    {...

  • How can I split this program into two classes? import java.io.*; public class Quiz { static...

    How can I split this program into two classes? import java.io.*; public class Quiz { static LineNumberReader cin = new LineNumberReader(new InputStreamReader(System.in)); public static void main(String[] args) { int score = 0; final int NumberofQuestions = 5; int num;    System.out.println("\nWelcome to CSC 111 Java Quiz\n");    String[][] QandA = { {"All information is stored in the computer using binary numbers: ","true"}, {"The word \"Public\" is a reserved word: ","false"}, {"Variable names may begin with a number: ","false"}, {"Will the...

  • Need help with this Java. I need help with the "to do" sections. Theres two parts...

    Need help with this Java. I need help with the "to do" sections. Theres two parts to this and I added the photos with the entire question Lab14 Part 1: 1) change the XXX to a number in the list, and YYY to a number // not in the list 2.code a call to linearSearch with the item number (XXX) // that is in the list; store the return in the variable result 3. change both XXX numbers to the...

  • I have this code but when there's 0 pennies, it doesn't output "and 0 pennies" at...

    I have this code but when there's 0 pennies, it doesn't output "and 0 pennies" at all, it is just left blank. package edu.wit.cs.comp1050; /** * Solution to the third programming assignment * When it runs it outputs the amount in quarters, dimes, nickels and pennies * * @author Rose Levine * */ import java.util.Scanner; public class PA1c {       /**    * Error message to display for negative amount    */    public static final String ERR_MSG =...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • I need help asking the user to half the value of the displayed random number as...

    I need help asking the user to half the value of the displayed random number as well as storing each number generated by the program into another array list and displayed after the game is over at the end java.util.*; public class TestCode { public static void main(String[] args) { String choice = "Yes"; Random random = new Random(); Scanner scanner = new Scanner(System.in);    ArrayList<Integer> data = new ArrayList<Integer>(); int count = 0; while (!choice.equals("No")) { int randomInt =...

  • I need a java flowchart for the following code: import java.util.*; public class Main {   ...

    I need a java flowchart for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");       ...

  • please illistrate a UML diagram for the following code bellow, it should have 3 rows, 1...

    please illistrate a UML diagram for the following code bellow, it should have 3 rows, 1 colum like the one bellow, first box should have the class name, second box is for class attributes, and third box should have the class operations/methods and please put a (+) for public and a (-) for private example: class +-attributes +-Operations Also make a JAVADOCs, but not generated by a compiler, to explain what is going on in the code import java.util.Random; public...

  • 23.1 Append to Oversize Array Java Help Given an oversize array with size1 elements and a...

    23.1 Append to Oversize Array Java Help Given an oversize array with size1 elements and a second oversize array with size2 elements, write a method that returns the first array with the elements of the second appended to the end. If the capacity of the oversize array is not large enough to append all of the elements, append as many as will fit. Hint: Do not construct a new array. Instead, modify the contents of the oversize array inside the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT