1
+ import { binarySearchIterative } from './binary_search'
2
+
1
3
/**
2
4
* @description Exponential search algorithm for a sorted array.
3
5
*
4
6
* The algorithm searches for a specific value in a sorted array by first finding a range
5
7
* where the value may be present and then performing a binary search within that range.
6
8
*
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
+ *
7
14
* @param {number[] } array - sorted list of numbers
8
15
* @param {number } x - target number to search for
9
16
* @return {number | null } - index of the target number in the list, or null if not found
@@ -26,24 +33,9 @@ export const exponentialSearch = (
26
33
i = i * 2
27
34
}
28
35
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 )
31
39
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
49
41
}
0 commit comments