forked from IamBisrutPyne/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearchUsingRecursion.java
More file actions
61 lines (49 loc) · 1.48 KB
/
LinearSearchUsingRecursion.java
File metadata and controls
61 lines (49 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Program Title: Linear Search (Recursive)
* Author: v-technoid
* Date: 2025-10-13
*
* Description: Searches for a target element in an array using a recursive linear search approach.
*
* Language: Java
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
import java.io.*;
import java.util.Scanner;
/**
* This program demonstrates the implementation of a linear search algorithm using recursion.
* It searches for a given key within an array of integers.
*/
public class LinearSearchRecursion{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int n = in.nextInt();
// Input array
int[] arr = new int[n];
System.out.println("Enter the array elements (one by one): ");
for (int i = 0; i < n; ++i) {
arr[i] = in.nextInt();
}
System.out.println("Enter the element to find:");
int key = in.nextInt();
int index = linearSearch(arr, 0, key);
if (index == -1) {
System.out.println("Key not found :(");
} else {
System.out.println("Key found at " + (index + 1) + " position");
}
}
// Find the Key/Element
public static int linearSearch (int[] arr, int ind, int key) {
if (arr.length == ind) {
return -1;
}
if (arr[ind] == key) {
return ind;
}
return linearSearch(arr, ind + 1, key);
}
}