Skip to content

Commit b7e9c85

Browse files
authored
Enhance LinearSearch with null check for value (#7355)
Added null check for the search value in the find method.
1 parent f38d5cd commit b7e9c85

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/main/java/com/thealgorithms/searches/LinearSearch.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
package com.thealgorithms.searches;
1515

1616
import com.thealgorithms.devutils.searches.SearchAlgorithm;
17+
1718
/**
1819
* Linear Search is a simple searching algorithm that checks
1920
* each element of the array sequentially until the target
@@ -33,7 +34,6 @@
3334
* @see BinarySearch
3435
* @see SearchAlgorithm
3536
*/
36-
3737
public class LinearSearch implements SearchAlgorithm {
3838

3939
/**
@@ -45,14 +45,17 @@ public class LinearSearch implements SearchAlgorithm {
4545
*/
4646
@Override
4747
public <T extends Comparable<T>> int find(T[] array, T value) {
48-
if (array == null || array.length == 0) {
48+
49+
if (array == null || array.length == 0 || value == null) {
4950
return -1;
5051
}
52+
5153
for (int i = 0; i < array.length; i++) {
52-
if (array[i].compareTo(value) == 0) {
54+
if (array[i] != null && array[i].compareTo(value) == 0) {
5355
return i;
5456
}
5557
}
58+
5659
return -1;
5760
}
5861
}

0 commit comments

Comments
 (0)