Skip to content

Commit 9d54909

Browse files
author
Farheen Shabbir Shaikh
committed
Add Linear Search algorithm in Java with comments
1 parent c0601d0 commit 9d54909

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Search/LinearSearch.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* LinearSearch.java
3+
* This program implements the Linear Search algorithm.
4+
* Time Complexity: O(n)
5+
*/
6+
7+
public class LinearSearch {
8+
9+
public static int linearSearch(int[] arr, int target) {
10+
// Traverse each element in the array
11+
for (int i = 0; i < arr.length; i++) {
12+
if (arr[i] == target) {
13+
return i; // Found the target at index i
14+
}
15+
}
16+
return -1; // Target not found
17+
}
18+
19+
public static void main(String[] args) {
20+
int[] numbers = {5, 8, 12, 20, 35};
21+
int target = 20;
22+
23+
int index = linearSearch(numbers, target);
24+
if (index != -1) {
25+
System.out.println("Target " + target + " found at index: " + index);
26+
} else {
27+
System.out.println("Target " + target + " not found in the array.");
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)