88 *
99 * @param {number[] } array - sorted list of numbers
1010 * @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
1212 * @see [BinarySearch](https://www.geeksforgeeks.org/binary-search/)
1313 * @example binarySearch([1,2,3], 2) => 1
14- * @example binarySearch([4,5,6], 2) => -1
14+ * @example binarySearch([4,5,6], 2) => null
1515 */
1616
1717export const binarySearchIterative = (
1818 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
2724
2825 // 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
3030
3131 while ( array [ middle ] !== target && start <= end ) {
3232 // 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 = (
3737 middle = ( start + end ) >> 1
3838 }
3939 // return the middle index if it is equal to target
40- return array [ middle ] === target ? middle : - 1
40+ return array [ middle ] === target ? middle : null
4141}
4242
4343export const binarySearchRecursive = (
4444 array : number [ ] ,
4545 target : number ,
4646 start = 0 ,
4747 end = array . length - 1
48- ) : number => {
49- if ( array . length === 0 ) return - 1
48+ ) : number | null => {
49+ if ( array . length === 0 ) return null
5050
5151 // 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
5353
5454 const middle = ( start + end ) >> 1
5555
5656 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
5858
5959 // if the target is less than the middle value, move the end pointer to be middle -1 to narrow the search space
6060 // otherwise, move the start pointer to be middle + 1
0 commit comments