Linear Search in Array
This program performs linear search to find an element in an array.
Problem Statement
Write a Java program to search for a given element in an integer array using linear search.
Source Code
| 1 | public class LinearSearch { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {10, 25, 30, 45, 50}; |
| 4 | int key = 30; |
| 5 | boolean found = false; |
| 6 | for(int i=0; i<arr.length; i++) { |
| 7 | if(arr[i] == key) { |
| 8 | System.out.println("Element found at index: " + i); |
| 9 | found = true; |
| 10 | break; |
| 11 | } |
| 12 | } |
| 13 | if(!found) System.out.println("Element not found"); |
| 14 | } |
| 15 | } |
Program Output
Element found at index: 2
Explanation
The variable key stores the value to search, and the for loop checks each element against key, printing the index and breaking the loop if a match is found, otherwise a not-found message displays, demonstrating the linear search algorithm.