Skip to content

Commit a07f4ac

Browse files
author
numan
committed
Add Linear Search algorithm in Java
1 parent 763b95b commit a07f4ac

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.searches;
2+
3+
/*
4+
* Linear Search Algorithm
5+
* Time Complexity: O(n)
6+
* Space Complexity: O(1)
7+
*/
8+
9+
public class LinearSearch {
10+
11+
// Method to perform linear search
12+
public static int linearSearch(int[] arr, int target) {
13+
for (int i = 0; i < arr.length; i++) {
14+
if (arr[i] == target) {
15+
return i; // element found
16+
}
17+
}
18+
return -1; // element not found
19+
}
20+
21+
// Main method for testing
22+
public static void main(String[] args) {
23+
int[] arr = {10, 20, 30, 40, 50};
24+
int target = 30;
25+
26+
int result = linearSearch(arr, target);
27+
28+
if (result != -1) {
29+
System.out.println("Element found at index: " + result);
30+
} else {
31+
System.out.println("Element not found");
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)