Java Program to search an element in an array .
Objective
Write a Java program to search for a specific element in an array (Linear Search).
Algorithm / Approach
- Initialize a hardcoded array of integers.
- Prompt the user to enter the element
xto search for. - Set a boolean flag variable (
flag) to 0. - Start a
forloop to iterate through the array. - If
a[i] == x, setflag = 1, record the position, and immediatelybreakout of the loop. - After the loop, check the flag. If it's 0, print "Element not found". Otherwise, print the position.
Test.java
import java.util.Scanner;
class Test {
void search(int x) {
int a[]={1,10,20,30,40};
int i,flag = 0;
for(i=0; i< a.length; i++){
if(a[i]==x){
flag = 1;
break;
}
}
if(flag==0) {
System.out.print("Element not Found");
}
else {
System.out.print("Found at "+(i+1));
}
}
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Element: ");
int x = s.nextInt();
Test t = new Test();
t.search(x);
}
}
Expected Output
Enter Element: 30 Found at 3
Explanation of the Program
- This algorithm is called Linear Search. It scans the array sequentially from the first element to the last.
- The
flagvariable acts as a memory marker to remember if we succeeded during the loop. - The
breakstatement is an important optimization: once the element is found, there is no need to check the rest of the array, saving processing time.
Complexity
Time Complexity
O(n) - In the worst-case scenario, the element is at the very end or doesn't exist.
Space Complexity
O(1)