Skip to content

Commit 69767aa

Browse files
authored
algorithm: linear search (#75)
1 parent 8601487 commit 69767aa

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Search/LinearSearch.ts

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @function linearSearch
3+
* @description linear search is the simplest search possible in a array
4+
* it has a linear cost, if the value is present in the array, then the index of the first occurence will be returned
5+
* if it's not present, the return it will be -1
6+
* @param {number[]} array - list of numbers
7+
* @param {number} target - target number to search for
8+
* @return {number} - index of the target number in the list, or -1 if not found
9+
* @see https://en.wikipedia.org/wiki/Linear_search\
10+
* @example linearSearch([1,2,3,5], 3) => 2
11+
* @example linearSearch([1,5,6], 2) => -1
12+
*/
13+
export const linearSearch = (array: any[], target: any): number => {
14+
for (let i = 0; i < array.length; i++) {
15+
if (array[i] === target) return i;
16+
}
17+
return -1;
18+
}

Search/test/LinearSearch.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { linearSearch } from "../LinearSearch";
2+
3+
describe("Linear search", () => {
4+
test.each([
5+
[['o', 'b', 'c'], 'c', 2],
6+
[[1, 2, 3, 4, 5], 4, 3],
7+
[['s', 't', 'r', 'i', 'n', 'g'], 'a', -1]
8+
])(
9+
"of %o , searching for %o, expected %i",
10+
(array: any[], target: any, index: number) => {
11+
expect(linearSearch(array, target)).toStrictEqual(index)
12+
},
13+
);
14+
});

0 commit comments

Comments
 (0)