Linear Search with Early Exit
This program performs linear search with early exit optimization.
Problem Statement
Write a Java program to search for a given element in an integer array using linear search with early exit.
Source Code
| 1 | public class OptimizedLinearSearch { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Optimized Linear Search"); |
| 4 | int[] arr = {10, 20, 30, 40, 50}; |
| 5 | int key = 40; |
| 6 | for(int i=0; i<arr.length; i++) { |
| 7 | if(arr[i] == key) { |
| 8 | System.out.println("Element found at index: " + i); |
| 9 | return; // early exit |
| 10 | } |
| 11 | } |
| 12 | System.out.println("Element not found"); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Optimized Linear Search Element found at index: 3
Explanation
The for loop iterates through the array and, upon finding a match with key, immediately returns from main rather than continuing to iterate, reducing unnecessary iterations and demonstrating optimized linear search.