Hey guys, Welcome to flower brackets blog. Today you will learn linear search in java.

Linear search java is very simple sequential search algorithm. It’s used to search key element exists in the given array or not.

Here search starts from leftmost element of an array and key element is compared with every element in an array.

Also read – sort string array java

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.

Also read – binary search in java

Let’s see java program,

public class LinearSearchDemo { // here function returns index of element x in arrLinear static int searchNumber(int arrLinear[], int n) { int num = arrLinear.length; for(int a = 0; a < num; a++) { // here we are returning the index of the element if found if(arrLinear[a] == n) return a; } // here we are returning -1 if element is not found return -1; } public static void main(String[] args) { int arrNum[] = {15, 25, 35, 55, 75, 95}; int key = 55; int output =searchNumber(arrNum, key); if(output == -1) { System.out.print("Sorry!!Element is not present"); } else { System.out.print("Element is present at index " + output); } } }

**Output:**

Element is present at index 3

#### 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 **order of n time**, that is, **O(n)**.

Also read – sparse matrix java