Check whether an element is present in an array or not in Java

In this tutorial, we are going to check whether an element is present in an array or not in Java.

To do this, various search techniques can be implemented like linear search (one of the sequential search techniques), binary search (one of the interval search techniques) and many more search techniques( like jump search, exponential search and so on).

Today we will check out the most basic technique which is linear search.

Linear Search: Checking whether an element is present or not

Linear search is the simplest way to check if an element is present or not in an array.
It is slow but it works. It’s like brute force method of solving this problem.
In linear search, every element in the array is compared with the key(the element to be searched).
Below are the steps to check an elements(key) presence.

Steps to check if key exists in Array A[] of size n:

  1. Set i to 0
  2. Check if A[i] equals key: return i if true and end search
  3. Increase i by 1
  4. If i less than n, go to step 2. Otherwise, search terminates and key is not found.

Program:

public class Main
{
  public static void LinearSearch(int[] A,int key){
      
      for(int i=0;i<A.length;i++){ 
          if(A[i]==key){//checking if the array element is same as the key
              System.out.println("Key found at position "+(i+1));
              return;	      
          }
      }
      System.out.println("Element not found");
  }

  public static void main(String[] args) {
    int[] arr = { 25, 65, 1, 9, 64 }; 
    LinearSearch(arr, 65);
  }
}
Output:
Key found at position 2

Here, array and key are taken as parameters of the method LinearSearch. If the element is present then it’s position in the array is printed (here i+1 is printed as array indexing starts from zero) else “element not found is printed”.

 

How efficient is this method?

This is the most efficient method to search for an element. But, it has it’s drawbacks like,

  1. What if the size of the array is large(more than 100), then the time complexity to search increases?
  2. This is the worst-case scenario, What if the element is not present or the key is in the last position then the search takes place till the end of the array and this is not a feasible process.

Leave a Reply

Your email address will not be published. Required fields are marked *