The list of array is traversed sequentially and every element is checked. In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match found then location of the item is returned otherwise the algorithm return NULL.

Example:
public class LinearSearch {
public static void main(String str[]) {
int[] items = new int[]{3,4,5,7,8,9,12};
int index = linearSearch(items, 9);
System.out.println("Found " + items[index] + " at index : " + index);
}
public static int linearSearch(int[] items, int element) {
for (int i = 0; i < items.length; i++) {
if (items[i] == element) {
return i;
}
}
return -1;
}
}
Output:
Found 9 at index : 5
Well, when we find the value at the given index position, we’re just exit and return the index. It is an example of small optimization but this is still linear growth rate algorithm.

Leave a comment