Linear Search Source Code in Java

In this source code example, we will write a Java program to demonstrate how to implement the Linear Search algorithm in Java.

Linear search is a simple search algorithm that sequentially checks each element of a list until the target element is found or the end of the list is reached. It is also known as a sequential search.

Linear Search Source Code in Java

public class LinearSearch {

   public int search(int[] arr, int n, int x) {
      // edge case
      if (arr == null || arr.length == 0) {
         throw new IllegalArgumentException("Invalid input");
      }

      for (int i = 0; i < n; i++) {
         if (arr[i] == x) {
            return i;
         }
      }
      return -1;
   }

   public static void main(String[] args) {
      int[] arr = { 5, 1, 9, 2, 10, 15, 20 };
      LinearSearch ls = new LinearSearch();
      System.out.println(ls.search(arr, arr.length, 20));
   }
}

Output:

6
Linear search has a time complexity of O(n), where n is the number of elements in the list. This means that the search time increases linearly with the size of the list. 

Linear search is not very efficient when the list is large, but it can be useful for small lists or when the element order is not known in advance.

There are other search algorithms that are more efficient for larger lists, such as binary search and hash table search.

Comments