Skip to content

Commit 61b1d22

Browse files
committed
fix: added parameters to iterative binary search
1 parent 44b698d commit 61b1d22

File tree

2 files changed

+17
-25
lines changed

2 files changed

+17
-25
lines changed

search/binary_search.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,18 @@
1616

1717
export const binarySearchIterative = (
1818
array: number[],
19-
target: number
19+
target: number,
20+
start: number = 0,
21+
end: number = array.length - 1
2022
): number => {
2123
if (array.length === 0) return -1
2224

23-
// declare pointers for the start, middle and end indices
24-
let start = 0,
25-
end = array.length - 1,
26-
middle = (start + end) >> 1
27-
2825
// ensure the target is within the bounds of the array
2926
if (target < array[start] || target > array[end]) return -1
3027

28+
// declare pointers for the middle index
29+
let middle = (start + end) >> 1
30+
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
3333
// otherwise, move the start pointer to be middle + 1

search/exponential_search.ts

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
import { binarySearchIterative } from './binary_search'
2+
13
/**
24
* @description Exponential search algorithm for a sorted array.
35
*
46
* The algorithm searches for a specific value in a sorted array by first finding a range
57
* where the value may be present and then performing a binary search within that range.
68
*
9+
* Compared with binary search, exponential search can be more convenient and advantageous
10+
* in cases where the element to be searched is closer to the beginning of the array,
11+
* thus avoiding several comparisons that would make the search more verbose.
12+
* Exponential search doubles the search time with each iteration.
13+
*
714
* @param {number[]} array - sorted list of numbers
815
* @param {number} x - target number to search for
916
* @return {number | null} - index of the target number in the list, or null if not found
@@ -26,24 +33,9 @@ export const exponentialSearch = (
2633
i = i * 2
2734
}
2835

29-
return binarySearch(array, x, i / 2, Math.min(i, arrayLength - 1))
30-
}
36+
const start = Math.floor(i / 2)
37+
const end = Math.min(i, arrayLength - 1)
38+
const result = binarySearchIterative(array, x, start, end)
3139

32-
const binarySearch = (
33-
array: number[],
34-
x: number,
35-
start: number,
36-
end: number
37-
): number | null => {
38-
while (start <= end) {
39-
const mid = Math.floor((start + end) / 2)
40-
if (array[mid] === x) {
41-
return mid
42-
} else if (array[mid] < x) {
43-
start = mid + 1
44-
} else {
45-
end = mid - 1
46-
}
47-
}
48-
return null
40+
return result !== -1 ? result : null
4941
}

0 commit comments

Comments
 (0)