I've spent like an hour trying to figure this one out and I couldn't. This is an exercise for a Java elective course I am taking and I could use some help.
Write a method linearSearch() that takes an array of integers, and an integer value. It should then return the index of the value inside the array (by using a for loop to traverse the elements one by one in order). If the value is not found, -1 should be returned. If more than one value is found, the first occurrence should be returned. Write a program to test your method.
So this is what I tried doing.
public class Exercise6 {
public static void main(String [] args) {
int[] a = {3, 6, 70, 3, 7, 9};
linearSearch(a, 3);
}
public static void linearSearch(int[] a, int n){
int index;
for (int i = 0; i < a.length; i++){
if (a[i] == n){
index = i;
break;
}
else {
index = -1;
}
}
System.out.print(index);
}
}
But this is obviously wrong. Could you please point me in the right direction? I don't necessarily want you to give me the answer, just give me an idea about the steps.