Linear Search Algorithm
- Linear Search checks each element one by one until it finds the target.
- Works on unsorted or sorted arrays.
- Time Complexity: O(n)
- Space Complexity: O(1)
Iterative Linear Search
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; // Element found, return index
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] arr = {4, 2, 7, 1, 9, 5};
int target = 7;
int index = linearSearch(arr, target);
if (index != -1)
System.out.println("Element found at index: " + index);
else
System.out.println("Element not found!");
}
}
✅ Output:
Element found at index: 2
Recursive Linear Search
public class LinearSearchRecursive {
public static int linearSearch(int[] arr, int index, int target) {
if (index >= arr.length) {
return -1; // Base case: not found
}
if (arr[index] == target) {
return index; // Found
}
return linearSearch(arr, index + 1, target); // Search next element
}
public static void main(String[] args) {
int[] arr = {4, 2, 7, 1, 9, 5};
int target = 1;
int index = linearSearch(arr, 0, target);
if (index != -1)
System.out.println("Element found at index: " + index);
else
System.out.println("Element not found!");
}
}
Notes:
- Linear Search is simple but inefficient for large arrays.
- Use Binary Search if the array is sorted for faster lookup.
- Works for arrays of any data type, not just integers.