-
Notifications
You must be signed in to change notification settings - Fork 1
/
028_LinearSearch.java
86 lines (71 loc) · 2.7 KB
/
028_LinearSearch.java
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.Scanner;
public class LinearSearch {
/**
* Linear Search => TC = O(n), SC = O(1)
* This approach iterates through the array to find the element.
* Time Complexity: O(n) - each element is checked until the target is found or the end of the array is reached.
* Space Complexity: O(1) - uses constant space for variables.
*/
/*
public static int linearSearch(int[] arr, int key) {
// Traverse the array
for(int i=0; i<arr.length; i++) {
// Check if the current element is equal to the key
if(arr[i] == key) {
// Return the index if found
return i;
}
}
// Return -1 if the key is not found
return -1;
}
*/
/**
* Approach - 2: Using Recursion => TC = O(n), SC = O(n)
* This approach uses recursion to perform a linear search.
* Time Complexity: O(n) - each element is checked until the target is found or the end of the array is reached.
* Space Complexity: O(n) - due to recursive calls on the stack.
*/
// Helper method for recursion
public static int helper(int[] arr, int i, int key) {
// Base case: if index reaches array length, key is not found
if (i == arr.length)
return -1;
// Check if the current element is equal to the key
if (arr[i] == key) {
// Return the index if found
return i;
}
// Recursive call to check the next element
return helper(arr, i + 1, key);
}
// Main method for recursive linear search
public static int linearSearch(int[] arr, int key) {
// Start the recursive search from index 0
return helper(arr, 0, key);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter size of the array: ");
int n = sc.nextInt();
int[] arr = new int[n];
// Input: Array elements
System.out.println("Enter array elements: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
// Input: Element to find in the array
System.out.print("Enter element to find in array: ");
int key = sc.nextInt();
// Perform linear search
int result = linearSearch(arr, key);
// Output: Result of the search
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index " + result);
}
sc.close();
}
}