Question: in java Background: Applying linear search and binary search on arrays. Step 1: Search class Implement a Search class that will contain methods for linear
in java
Background: Applying linear search and binary search on arrays.
Step 1: Search class
Implement a Search class that will contain methods for linear search and binary search. Implement 2 linear search methods (one for integers and one for Strings). Also, implement 2 binary search methods (one for integers and one for Strings). The methods will take 2 parameters: an array and a search item, and will return the location of the item in the array if found, or -1 if not found.
Search Class
Methods:
public static int linearSearch( int[] values, int searchValue)
public static int linearSearch( String[] words, String searchWord)
public static int linearSearch( int[] values, int searchValue)
public static int linearSearch( String[] words, String searchWord)
Sample code for linear search and binary search (integer versions) is given below. Both examples work on a sample array of integers called values, and an integer parameter variable called searchValue.
Linear Search
for(inti=0;i if(values[i]==searchValue){ returni; } } return 1; Binary Search booleanfound=false; intlow=0,pos=0,high=values.length 1; while(low<=high&&!found){ pos=(low+high)/2;//Midpoint of the subsequence if (values[pos]==searchValue){ found=true;}. //Found it! else if(values[pos] < searchValue){ low=pos+1;}. //. Look in second half else{ high=pos 1;}. // Look in first half } if(found){ return pos; } else{ return 1; } *Note that for the String version of the methods, you will need to use the .equals() and the .compareTo() methods. Step 2: RunSearch class Create another class, RunSearch, that will contain a main method where you will demonstrate how to use the Search class and its methods. The array data can be coded into the main method, while the search values or words will be entered by the user. *Note that the arrays needs to be sorted before applying the binary search algorithm. Use the built-in Arrays.sort(...) method to sort your values array. int[]myArray={75, 80 , 20 , 10 , 50 ,5 ,17 ,15 ,100 ,40}; Prompt the user to enter a value to search for and save it into a variable. Then, apply the linear search and binary search to display the location of the value, or indicate not found. Then, do the same for the String version. Remember that a static method is called with the class name, as follows: Calling a static method of the Search class in the main method of the Run Search class: int result=Search.linearSearch(myArray, mySearchValue);
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
