Linear Search program in java
Java Program for Linear Search (With Example & Explanation)
Introduction
Linear Search is one of the simplest searching algorithms in Java. It is used to find a specific element in an array by checking each element one by one.
This method is easy to understand and works well for small datasets.
Problem Statement
Write a Java program to perform a Linear Search.
Solution
import java.io.*;
public class LinearSearch {
public static void main(String args[]) throws IOException {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
int i, s, n, h = 0;
// Taking array size input
System.out.println("Enter length of Array:");
n = Integer.parseInt(br.readLine());
int A[] = new int[n];
// Taking array elements input
System.out.println("Enter array elements:");
for (i = 0; i < n; i++) {
A[i] = Integer.parseInt(br.readLine());
}
// Display array elements
System.out.println("Array elements are:");
for (i = 0; i < n; i++) {
System.out.println(A[i]);
}
// Input element to search
System.out.println("Enter element to be searched:");
s = Integer.parseInt(br.readLine());
// Linear search logic
for (i = 0; i < n; i++) {
if (s == A[i]) {
System.out.println("Element found at position: " + (i + 1));
h = 1;
break;
}
}
// If element not found
if (h == 0) {
System.out.println("Element not found");
}
}
}
Explanation
- The program first takes the size of the array as input.
- Then it reads all array elements from the user.
- After that, it asks for the element to be searched.
- Using a loop, it compares each element with the target value.
- If a match is found, it prints the position of the element.
- If no match is found, it displays "Element not found".
Sample Output
Case 1: Element Found
Enter length of Array:
5
Enter array elements:
10
20
30
40
50
Array elements are:
10
20
30
40
50
Enter element to be searched:
30
Element found at position: 3
Case 2: Element Not Found
Enter length of Array:
5
Enter array elements:
10
20
30
40
50
Enter element to be searched:
60
Element not found
Key Points
- Linear Search checks elements sequentially.
- Time Complexity: O(n)
- Best for small datasets or unsorted arrays.
- Easy to implement and understand.
Conclusion
Linear Search is a basic but important concept in programming. It helps beginners understand how searching works before moving to advanced algorithms like Binary Search.
Comments
Post a Comment
Hello students
If you have any doubt then let me know.