Google News
logo
Java Program for Linear Search
In the following examples of Java program for Linear Search :
Program :
public class LinearSearch {

    public static void main(String[] args) {
        int[] arr = {5, 7, 2, 10, 4};
        int key = 10;
        int index = linearSearch(arr, key);
        if (index == -1) {
            System.out.println("Element not found in array");
        } else {
            System.out.println("Element found at index " + index);
        }
    }

    public static int linearSearch(int[] arr, int key) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
Output :
Element found at index 3
In this program, we first declare an integer array arr and initialize it with the values 5, 7, 2, 10, and 4. We also declare an integer variable key and initialize it with the value 10, which is the element we want to search for.

We then call the linearSearch method and pass the array and the key as arguments. This method performs a linear search on the array and returns the index of the first occurrence of the key, or -1 if the key is not found.

Finally, we print the result of the linear search. If the index returned by the method is -1, we print "Element not found in array".

Otherwise, we print "Element found at index" followed by the index.