Skip to content

added LinearSearchRecursive.java and updated README.md #362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1469,8 +1469,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- Java -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/java/LinearSearchRecursive.java">
<img align="center" height="25" src="./logos/java.svg" />
</a>
</td>
<td> <!-- Python -->
Expand Down
49 changes: 49 additions & 0 deletions src/java/LinearSearchRecursive.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import java.util.Scanner;

public class LinearSearchRecursive {

public static int linearSearchRecursive(int[] arr, int n, int index, int target) {
// Base case: If index exceeds array bounds, return -1 indicating target is not found
if (index >= n) {
return -1;
}

// If the current element matches the target, return the index
if (arr[index] == target) {
return index;
}

// Recursive case: move to the next index in the array
return linearSearchRecursive(arr, n, index + 1, target);
}

public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();

int[] arr = new int[n];

System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter the element you need to search for in the array: ");
int target = scanner.nextInt();

// Call the recursive linear search function
int result = linearSearchRecursive(arr, n, 0, target);

if (result >= 0) {
System.out.println("Target element found at index: " + result);
} else {
System.out.println("Target element not found.");
}

// Close the scanner to avoid memory leaks
scanner.close();
}
}