Linear searches are used to find a value in a list by checking each element one at a time in order. The elements that need to be searched are stored in an array so that they can be iterated through with a for loop to check for the value. When the that value is found, the algorithm returns the index of the found element. Linear searches work best when the list has only a few elements or when only performing a single search, for example, finding a specific grade.
public class LinearSearch {
public static void main(String[] args) {
int[] values = {2, 5, 6, 3, 10, 9, 6, 2, 8};
System.out.println(linearSearch(values, 2, 3));
}
public static int linearSearch(int arr[], int key, int start){
for(int i =start; i < arr.length; i++){
if (arr[i] == key){
return i; //returns index of number searching
}
}
return -1;
}
}
7