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
+ } ) ;
0 commit comments