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;
}
}
Element found at index 3
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.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.-1
, we print "Element not found in array".