๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Linear Search Algorithm in DSA (Java)  


Introduction
  • Linear Search is a simple searching technique used to find a particular element in an array or list.
  • It checks each element one by one until the desired element is found or the array ends.
  • It is also called sequential search.
  • Logic / Steps (Simple):
    1. Start searching from the first element of the array.
    2. If the element matches, print its index position and stop.
    3. If not, keep checking the next element until found or array ends. If not found, return -1.
Linear Search Algorithm in Java DSA
  • Program:
    public class LinearSearchExample
    {
        public static void main(String[] args)
        {
            int[] arr = {10, 20, 30, 40, 50};
        
            int key = 30;
            boolean found = false;
    
            // Linear search
            for (int i = 0; i < arr.length; i++)
            {
                if (arr[i] == key)
                {
                    System.out.println("Element found at index: " + i);
                    found = true;
                    break;
                }
            }
    
            if (!found)
            {
                System.out.println("Element not found");
            }
        }
    }

Important Points to Note :-
  • Linear Search is simple and easy to implement, but not efficient for large datasets.
  • Linear Search can work on unsorted arrays.
  • Time Complexity for Linear Search:
    • Case Description No. of Comparisons Time Complexity
      Worst Case The element is either at the last position or not present in the array. n O(n)
      Average Case The element is found somewhere in the middle of the array. n/2 ฮ˜(n)
      Best Case The element is found at the first position. 1 ฮฉ(1)
  • Space Complexity:
    • O(1) โ†’ only a few variables are used; no extra memory is needed.