Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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"));
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote