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

Array arr initialized with integers. - For loop iterates through elements. - If element matches key, index printed and program exits immediately. - Early exit reduces unnecessary iterations. - Together demonstrates optimized linear search. Conclusion: Shows how linear search can be optimized with early exit.

Quick Links to Explore