-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathLinearSearch.java
More file actions
58 lines (55 loc) · 1.4 KB
/
LinearSearch.java
File metadata and controls
58 lines (55 loc) · 1.4 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
/**
* Performs Linear Search on an array.
*
* Linear search checks each element one by one until the target is found
* or the array ends.
*
* Example:
* Input: [2, 4, 6, 8], target = 6
* Output: Index = 2
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
package com.thealgorithms.searches;
import com.thealgorithms.devutils.searches.SearchAlgorithm;
/**
* Linear Search is a simple searching algorithm that checks
* each element of the array sequentially until the target
* value is found or the array ends.
*
* It works for both sorted and unsorted arrays.
*
* Time Complexity:
* - Best case: O(1)
* - Average case: O(n)
* - Worst case: O(n)
*
* Space Complexity: O(1)
*
* @author Varun Upadhyay
* @author Podshivalov Nikita
* @see BinarySearch
* @see SearchAlgorithm
*/
public class LinearSearch implements SearchAlgorithm {
/**
* Generic Linear search method
*
* @param array List to be searched
* @param value Key being searched for
* @return Location of the key, -1 if array is null or empty, or key not found
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T value) {
if (array == null || array.length == 0) {
return -1;
}
for (int i = 0; i < array.length; i++) {
if (array[i].compareTo(value) == 0) {
return i;
}
}
return -1;
}
}