|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class LinearSearchRecursive { |
| 4 | + |
| 5 | + public static int linearSearchRecursive(int[] arr, int n, int index, int target) { |
| 6 | + // Base case: If index exceeds array bounds, return -1 indicating target is not found |
| 7 | + if (index >= n) { |
| 8 | + return -1; |
| 9 | + } |
| 10 | + |
| 11 | + // If the current element matches the target, return the index |
| 12 | + if (arr[index] == target) { |
| 13 | + return index; |
| 14 | + } |
| 15 | + |
| 16 | + // Recursive case: move to the next index in the array |
| 17 | + return linearSearchRecursive(arr, n, index + 1, target); |
| 18 | + } |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + // Create a scanner object to read user input |
| 22 | + Scanner scanner = new Scanner(System.in); |
| 23 | + |
| 24 | + System.out.print("Enter the size of the array: "); |
| 25 | + int n = scanner.nextInt(); |
| 26 | + |
| 27 | + int[] arr = new int[n]; |
| 28 | + |
| 29 | + System.out.println("Enter the elements of the array: "); |
| 30 | + for (int i = 0; i < n; i++) { |
| 31 | + arr[i] = scanner.nextInt(); |
| 32 | + } |
| 33 | + |
| 34 | + System.out.print("Enter the element you need to search for in the array: "); |
| 35 | + int target = scanner.nextInt(); |
| 36 | + |
| 37 | + // Call the recursive linear search function |
| 38 | + int result = linearSearchRecursive(arr, n, 0, target); |
| 39 | + |
| 40 | + if (result >= 0) { |
| 41 | + System.out.println("Target element found at index: " + result); |
| 42 | + } else { |
| 43 | + System.out.println("Target element not found."); |
| 44 | + } |
| 45 | + |
| 46 | + // Close the scanner to avoid memory leaks |
| 47 | + scanner.close(); |
| 48 | + } |
| 49 | +} |
0 commit comments