Let’s learn linear search in java.
Linear search in java
Linear search is very simple sequential search algorithm. It’s used to search key element in the given array. Here search starts from leftmost element of an array and key element is compared with every element in an array.

Search continues until the key element is found. If key element is found, index position is returned, else, -1 is returned.
Linear search is rarely used because it is practically very slow compared to binary search and hashing. Let’s see program on linear search.
class LinearSearchDemo { public static void main(String[] args) { int[] arrLinear = {15, 25, 35, 55, 75, 95}; int key = 55; int temp = 0; for (int i = 0; i < arrLinear.length; i++) { if (arrLinear[i] == key) { System.out.println("Element is present at index position " + i + "."); temp = temp + 1; } } if (temp == 0) { System.out.println("Element not found!!!"); } } }
Output:
Element is present at index position 3.
Now let’s see above program on linear search using strings.
class LinearSearchString { public static void main(String[] args) { String[] strNames = {"sandy", "rohit", "sarvesh", "dinesh", "akash", "bharat"}; String search = "sarvesh"; int temp = 0; for (int i = 0; i < strNames.length; i++) { if(strNames[i].equals(search)) { System.out.println("String is present in " + i + " index position."); temp++; } } if (temp == 0) { System.out.println("Element is not present in the given array."); } } }
Output:
String is present in 2 index position.
What is time complexity of linear search?
In general we can say, if we have “n” elements in an array to search an element in an array, it will take O(1) in best case, average of O(n) and worst case of O(n).
Also read – garbage collection in java