Skip to content

Commit 590f3ce

Browse files
committed
Add linear search algorithm implementation with tests and documentation
1 parent 7f92e5e commit 590f3ce

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Linear Search
2+
3+
Linear search is a searching algorithm that sequentially checks each element in a list until the desired element is found or the sequence ends.
4+
5+
## Time Complexity
6+
7+
- **Best Case:** **O(1)** (Element found at the beginning)
8+
- **Worst Case:** **O(n)** (Element at the end or not present)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export const linearSearch = <T>(
2+
array: T[],
3+
target: T
4+
): { index: number; element: T } | null => {
5+
const length = array.length
6+
for (let index = 0; index < length; index++) {
7+
const element = array[index]
8+
if (element === target) return { index, element }
9+
}
10+
11+
return null
12+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { linearSearch } from '../../../src/algorithms/searching/linearSearch'
3+
4+
describe('linearSearch', () => {
5+
describe('when the array is empty', () => {
6+
it('should return null', () => {
7+
expect(linearSearch([], 1)).toBeNull()
8+
})
9+
})
10+
11+
describe('when the target is in the list', () => {
12+
it('should return the target with its index', () => {
13+
const vectors = [
14+
{
15+
array: [0, 1, 2, 3, 4, 5],
16+
target: 1,
17+
expected: { index: 1, element: 1 }
18+
},
19+
{
20+
array: [5, 4, 3, 2, 1, 0],
21+
target: 1,
22+
expected: { index: 4, element: 1 }
23+
}
24+
]
25+
vectors.forEach(({ array, target, expected }) => {
26+
expect(linearSearch(array, target)).toStrictEqual(expected)
27+
})
28+
})
29+
})
30+
31+
describe('when the target is not in the list', () => {
32+
it('it should return null', () => {
33+
const vectors = [
34+
{
35+
array: [0, 1, 2, 3, 4, 5],
36+
target: 6,
37+
expected: null
38+
},
39+
{
40+
array: [5, 4, 3, 2, 1, 0],
41+
target: 6,
42+
expected: null
43+
}
44+
]
45+
vectors.forEach(({ array, target, expected }) => {
46+
expect(linearSearch(array, target)).toBeNull()
47+
})
48+
})
49+
})
50+
})

0 commit comments

Comments
 (0)