Skip to content

Commit 083196b

Browse files
lamnguyen2187felipernb
authored andcommitted
Add lowerBound implementation and unit tests
1 parent cc8c0a1 commit 083196b

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

src/algorithms/search/binarysearch.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,32 @@ const binarySearch = (sortedArray, element) => {
2222
return -1;
2323
};
2424

25-
module.exports = binarySearch;
25+
/**
26+
* lowerBound returns index of the first element greater than the search key
27+
* in logarithmic time (O(log n))
28+
*
29+
* @param Array
30+
* @param Number\String
31+
*
32+
* @return Number
33+
*/
34+
const lowerBound = (sortedArray, element) => {
35+
let lo = 0;
36+
let hi = sortedArray.length - 1;
37+
38+
while (lo <= hi) {
39+
const mid = ((hi - lo) >> 1) + lo;
40+
if (sortedArray[mid] > element) {
41+
hi = mid - 1;
42+
} else {
43+
lo = mid + 1;
44+
}
45+
}
46+
47+
return lo;
48+
};
49+
50+
module.exports = {
51+
binarySearch,
52+
lowerBound
53+
};

src/search.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Search algorithms
22
module.exports = {
33
bfs: require('./algorithms/search/bfs'),
4-
binarySearch: require('./algorithms/search/binarysearch'),
4+
binarySearch: require('./algorithms/search/binarysearch').binarySearch,
5+
lowerBound: require('./algorithms/search/binarysearch').lowerBound,
56
ternarySearch: require('./algorithms/search/ternary_search'),
67
dfs: require('./algorithms/search/dfs')
78
};

src/test/algorithms/searching/binarysearch.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const binarySearch = require('../../..').Search.binarySearch;
2+
const lowerBound = require('../../..').Search.lowerBound;
23
const assert = require('assert');
34

45
describe('Binary Search', () => {
@@ -13,3 +14,25 @@ describe('Binary Search', () => {
1314
assert.equal(binarySearch([1, 2, 3, 4, 5], 100), -1);
1415
});
1516
});
17+
18+
describe('Lower Bound', () => {
19+
it('finds the first element greater than search key', () => {
20+
let arr = [1, 2, 3, 4, 5];
21+
22+
assert.equal(lowerBound(arr, 0), 0);
23+
assert.equal(lowerBound(arr, 1), 1);
24+
assert.equal(lowerBound(arr, 2), 2);
25+
assert.equal(lowerBound(arr, 3), 3);
26+
assert.equal(lowerBound(arr, 4), 4);
27+
assert.equal(lowerBound(arr, 5), 5);
28+
assert.equal(lowerBound(arr, 6), 5);
29+
});
30+
31+
it('ignores duplicate values', () => {
32+
let duplicates = [1, 1, 2, 2, 3, 3];
33+
34+
assert.equal(lowerBound(duplicates, 1), 2);
35+
assert.equal(lowerBound(duplicates, 2), 4);
36+
assert.equal(lowerBound(duplicates, 3), 6);
37+
});
38+
});

0 commit comments

Comments
 (0)