Skip to content

Commit 7317833

Browse files
committed
Add example of a linear search algorithm
1 parent 16d098c commit 7317833

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy