Write a method called linearSearch that receives as input a variable, a, of type
ID: 3565992 • Letter: W
Question
Write a method called linearSearch that receives as input a variable, a, of type String array (String[]), as well as a target variable denoted t.
Your method should iterate through all the elements of a. While iterating through the different elements, if the target name matches an entry in a, you should return the position of the array at which the target was found. If the target is never found, the method should return -1.
For example, if the following array is passed to your method as argument,
{"Vladimir", "Ismail", "Priya", "Jiequn", "Melanie", "Camilo", "Jonathan"}
with the string "Melanie" as target. The method returns 4. On the other hand, using the same
array as input but with the string "BlipBlop123" as target, it returns ?1.
Explanation / Answer
class LinearSearch{
public static int linearSearch(String a[], String t){
for(int i=0 ; i< a.length; i++){
if(t.equals(a[i])){
return i;
}
}
return -1;
}
public static void main(String [] args){
String a[] = {"Vladimir", "Ismail", "Priya", "Jiequn", "Melanie", "Camilo", "Jonathan"};
System.out.println(linearSearch(a, "Priya"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.