Skip to content

Commit 3d5e3b5

Browse files
committed
add binary search tree
1 parent e65f6ad commit 3d5e3b5

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { describe, it, expect } from "bun:test";
2+
import { binarySearch } from "./binary-search";
3+
4+
describe('Binary Search Function', () => {
5+
const sortedArray = [0, 1, 2, 4, 5, 6, 44, 63, 87, 99, 283];
6+
7+
it('should return the index of the element when it exists', () => {
8+
const result = binarySearch(sortedArray, 5);
9+
expect(result).toBe(4); // 5 is at index 4
10+
});
11+
12+
it('should return -1 when the element does not exist', () => {
13+
const result = binarySearch(sortedArray, 100);
14+
expect(result).toBe(-1); // 100 is not in the array
15+
});
16+
17+
it('should return the index of the first element', () => {
18+
const result = binarySearch(sortedArray, 0);
19+
expect(result).toBe(0); // 0 is at index 0
20+
});
21+
22+
it('should return the index of the last element', () => {
23+
const result = binarySearch(sortedArray, 283);
24+
expect(result).toBe(10); // 283 is at index 10
25+
});
26+
27+
it('should return -1 for an empty array', () => {
28+
const result = binarySearch([], 1);
29+
expect(result).toBe(-1); // Searching in an empty array
30+
});
31+
32+
it('should handle an array with duplicate elements', () => {
33+
const arrayWithDuplicates = [1, 1, 1, 1, 1, 2, 3, 4, 5];
34+
const result = binarySearch(arrayWithDuplicates, 1);
35+
expect(result).toBe(0); // The first occurrence of 1 is at index 0
36+
});
37+
});
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Function này chưa handle trường hợp duplicate element trong array!
2+
export function binarySearch(array: number[], target: number): number {
3+
let left = 0;
4+
let right = array.length - 1;
5+
while (left <= right) {
6+
const middle = Math.floor((left + right) / 2);
7+
if (array[middle] === target) {
8+
return middle
9+
} else if (array[middle] < target) {
10+
// Target nằm bên phải
11+
left = middle + 1
12+
} else if (array[middle] > target) {
13+
// Target nằm bên trái
14+
right = middle - 1
15+
}
16+
}
17+
return -1
18+
}
19+
20+
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5));

0 commit comments

Comments
 (0)