File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
main/java/com/anverbogatov/algorithms/search
test/java/com/anverbogatov/algorithms/search Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .anverbogatov .algorithms .search ;
2
+
3
+ /**
4
+ * This class shows simple implementation of a linear search algorithm.
5
+ */
6
+ public final class LinearSearch {
7
+
8
+ public static final int NOT_FOUND = -1 ;
9
+
10
+ /**
11
+ * Search specific number in a given array of numbers using linear search algorithm.
12
+ * Linear search algorithm has O(n) complexity.
13
+ *
14
+ * @param numbers - given array of numbers in which search will be performed
15
+ * @param value - given value that must be found in the array
16
+ * @return index of the value in provided array or '-1' if not found
17
+ */
18
+ public static int linearSearch (int [] numbers , int value ) {
19
+ if (numbers .length == 0 ) {
20
+ return NOT_FOUND ;
21
+ }
22
+
23
+ for (int i = 0 ; i < numbers .length ; i ++) {
24
+ var el = numbers [i ];
25
+ if (el == value ) {
26
+ return i ;
27
+ }
28
+ }
29
+ return NOT_FOUND ;
30
+ }
31
+ }
Original file line number Diff line number Diff line change
1
+ package com .anverbogatov .algorithms .search ;
2
+
3
+ import org .junit .Assert ;
4
+ import org .junit .Test ;
5
+
6
+ import java .util .stream .IntStream ;
7
+
8
+ public class LinearSearchTest {
9
+
10
+ @ Test
11
+ public void testLinearSearchWithEmptyArray () {
12
+ // given
13
+ var numbers = new int []{};
14
+ // when
15
+ var index = LinearSearch .linearSearch (numbers , 0 );
16
+ // then
17
+ Assert .assertEquals (-1 , index );
18
+ }
19
+
20
+ @ Test
21
+ public void testLinearSearchWithSingleElementArrayHappy () {
22
+ // given
23
+ var numbers = new int []{47 };
24
+ // when
25
+ var index = LinearSearch .linearSearch (numbers , 47 );
26
+ // then
27
+ Assert .assertEquals (0 , index );
28
+ }
29
+
30
+ @ Test
31
+ public void testLinearSearchWithSingleElementArrayFailure () {
32
+ // given
33
+ var numbers = new int []{47 };
34
+ // when
35
+ var index = LinearSearch .linearSearch (numbers , 12 );
36
+ // then
37
+ Assert .assertEquals (-1 , index );
38
+ }
39
+
40
+ @ Test
41
+ public void testLinearSearch () {
42
+ // given
43
+ var numbers = IntStream .range (1 , 100 ).toArray ();
44
+ var n = 21 ;
45
+ // when
46
+ var index = LinearSearch .linearSearch (numbers , n );
47
+ //then
48
+ Assert .assertEquals (20 , index );
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments