-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathLinearSearch.java
More file actions
42 lines (39 loc) · 1.01 KB
/
LinearSearch.java
File metadata and controls
42 lines (39 loc) · 1.01 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
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
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T value) {
for (int i = 0; i < array.length; i++) {
if (array[i].compareTo(value) == 0) {
return i;
}
}
return -1;
}
}