DEV Community

Sudhakar V
Sudhakar V

Posted on

Linear Search

Linear search is a simple algorithm that checks each element in a list sequentially until the target value is found or the list ends.
Algorithm Steps

Start from the first element.

Compare each element with the target value.

If found, return its index.

If not found after checking all elements, return -1.
Enter fullscreen mode Exit fullscreen mode

package com.Example;
import java.util.Scanner;
public class LinearSearch {
public static void main(String[]args) {
int[] Ar = {100,52,45,};
Scanner sc = new Scanner(System.in);
System.out.println("Array");
int no = sc.nextInt();
for(int i=0;i<Ar.length;i++) {
if(Ar[i]==no) {
System.out.println("occur");

        break;
    } else {
        System.out.println("Not occur");
    }

}
sc.close();
Enter fullscreen mode Exit fullscreen mode

}
}

Time & Space Complexity

Time Complexity: O(n) (Worst case: checks all elements).

Space Complexity: O(1) (No extra space needed).
Enter fullscreen mode Exit fullscreen mode

When to Use Linear Search?

✔ Small datasets.
✔ Unsorted lists (since binary search requires sorting).
✔ Simple implementation.
Conclusion

Simple but inefficient for large datasets.

Works on any list (sorted or unsorted).

Easy to implement in Java.
Enter fullscreen mode Exit fullscreen mode

For faster searches, consider Binary Search (O(log n)) if the list is sorted. 🚀

Top comments (0)