8
8
*
9
9
* @param {number[] } array - sorted list of numbers
10
10
* @param {number } target - target number to search for
11
- * @return {number } - index of the target number in the list, or -1 if not found
11
+ * @return {number } - index of the target number in the list, or null if not found
12
12
* @see [BinarySearch](https://www.geeksforgeeks.org/binary-search/)
13
13
* @example binarySearch([1,2,3], 2) => 1
14
- * @example binarySearch([4,5,6], 2) => -1
14
+ * @example binarySearch([4,5,6], 2) => null
15
15
*/
16
16
17
17
export const binarySearchIterative = (
18
18
array : number [ ] ,
19
- target : number
20
- ) : number => {
21
- if ( array . length === 0 ) return - 1
22
-
23
- // declare pointers for the start, middle and end indices
24
- let start = 0 ,
25
- end = array . length - 1 ,
26
- middle = ( start + end ) >> 1
19
+ target : number ,
20
+ start : number = 0 ,
21
+ end : number = array . length - 1
22
+ ) : number | null => {
23
+ if ( array . length === 0 ) return null
27
24
28
25
// ensure the target is within the bounds of the array
29
- if ( target < array [ start ] || target > array [ end ] ) return - 1
26
+ if ( target < array [ start ] || target > array [ end ] ) return null
27
+
28
+ // declare pointers for the middle index
29
+ let middle = ( start + end ) >> 1
30
30
31
31
while ( array [ middle ] !== target && start <= end ) {
32
32
// if the target is less than the middle value, move the end pointer to be middle -1 to narrow the search space
@@ -37,24 +37,24 @@ export const binarySearchIterative = (
37
37
middle = ( start + end ) >> 1
38
38
}
39
39
// return the middle index if it is equal to target
40
- return array [ middle ] === target ? middle : - 1
40
+ return array [ middle ] === target ? middle : null
41
41
}
42
42
43
43
export const binarySearchRecursive = (
44
44
array : number [ ] ,
45
45
target : number ,
46
46
start = 0 ,
47
47
end = array . length - 1
48
- ) : number => {
49
- if ( array . length === 0 ) return - 1
48
+ ) : number | null => {
49
+ if ( array . length === 0 ) return null
50
50
51
51
// ensure the target is within the bounds of the array
52
- if ( target < array [ start ] || target > array [ end ] ) return - 1
52
+ if ( target < array [ start ] || target > array [ end ] ) return null
53
53
54
54
const middle = ( start + end ) >> 1
55
55
56
56
if ( array [ middle ] === target ) return middle // target found
57
- if ( start > end ) return - 1 // target not found
57
+ if ( start > end ) return null // target not found
58
58
59
59
// if the target is less than the middle value, move the end pointer to be middle -1 to narrow the search space
60
60
// otherwise, move the start pointer to be middle + 1
0 commit comments