Linear Search in Java
Linear search is a searching algorithm that sequentially checks each element in a list or array until the target value is found or the end of the list is reached. It compares the target value with each element one by one, starting from the beginning of the list. If the target value matches any element, the algorithm returns the index of that element. If the target value is not found in the list, the algorithm returns -1 to indicate that the target value is not present. Linear search has a time complexity of O(n), where n is the number of elements in the list.
JAVA PROGRAMMING
import java.util.*;
public class LinearSearchWithoutMethods {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
// Asking for the size of the array
System.out.println("Enter the size of the array:");
int size = scanner.nextInt();
// Creating an array to store the elements
int array[] = new int[size];
// Asking the user to input the array elements
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
// Asking for the element to search
System.out.println("Enter the element to search:");
int target = scanner.nextInt();
boolean found = false;
// Linear Search Algorithm
for (int i = 0; i < size; i++) {
if (array[i] == target) {
found = true;
System.out.println("Element " + target + " found at index " + i);
break; // Element found, exit loop
}
}
// If the element is not found
if (!found) {
System.out.println("Element " + target + " not found in the array.");
}
scanner.close();
}
}