Skip to content

Commit 43250c7

Browse files
Syed Fasiuddinmgechev
authored andcommitted
added linear search algorithm
1 parent bfc1287 commit 43250c7

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/searching/linearSearch.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
(function (exports) {
2+
'use strict';
3+
4+
/**
5+
* Searches for specific element in a given array
6+
* using the linear search algorithm
7+
* Time complexity: O(n)
8+
*
9+
* @param {Array} array Input array
10+
* @param {Number} key the number whose index is to be found
11+
* @returns {Number} the index of the first instance of number or else -1 if not found
12+
*/
13+
14+
const linearSearch = (array, key) => {
15+
for (let i = 0; i < array.length; i++) {
16+
if (array[i] == key) {
17+
return i;
18+
}
19+
}
20+
return -1;
21+
}
22+
23+
exports.linearSearch = linearSearch;
24+
})(typeof window === 'undefined' ? module.exports : window);

test/searching/linearSearch.spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
var linearSearch =
2+
require('../../src/searching/linearSearch').linearSearch;
3+
4+
describe('Linear Search', function () {
5+
'use strict';
6+
7+
it('should find the element at position 0 ', function () {
8+
expect(linearSearch([1, 2, 3, 4, 6, 8], 1)).toBe(0);
9+
});
10+
11+
it('should find the element in position arr.length - 1', function () {
12+
var arr = [1, 2, 3, 4, 6, 8];
13+
expect(linearSearch(arr, 8)).toBe(arr.length - 1);
14+
});
15+
16+
it('should work with arrays with 2 elements', function () {
17+
expect(linearSearch([1, 8], 1)).toBe(0);
18+
expect(linearSearch([1, 8], 8)).toBe(1);
19+
});
20+
21+
it('should return a negative number for missing elements', function () {
22+
expect(linearSearch([1, 2, 3], 4)).toBeLessThan(0);
23+
});
24+
25+
it('should work with empty arrays', function () {
26+
expect(linearSearch([], 4)).toBe(-1);
27+
});
28+
});

0 commit comments

Comments
 (0)