Input: arr[] = {9, 1, 3, 5, 7} X = 3
Output: Element found at index 2
Input: arr[] = {1, 2, 3, 4, 5, 7, 9} X = 6
Output: Element not found in the array
Linear Search Algorithm.
- If it matches, return the index.
- If it doesn't match, move to the next element.
Pseudo Code for Linear Search Algorithm.
function linearSearch(arr, target): for i from 0 to length of arr - 1: if arr[i] equals target: return i return -1
Java Program for Linear Search Algorithm.
// Java code for linear search algorithm to find and // return the index of searching element public class LinearSearch { public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; } public static void main(String[] args) { int[] arr = {4, 2, 7, 1, 9, 5}; int target = 7; int result = linearSearch(arr, target); if (result != -1) { System.out.println("Element found at index " + result); } else { System.out.println("Element not found in the array"); } } }
Element found at index 2- Time Complexity: In the worst case, linear search has a time complexity of O(n), where n is the number of elements in the array. This is because, in the worst scenario, we may have to go through the entire array to find the element.
- Space Complexity: Linear search has a constant space complexity of O(1). It doesn't require additional memory that scales with the size of the input.







