7
7
* value is found or the interval is empty.
8
8
*/
9
9
10
- function binarySearch ( arr , x , low = 0 , high = arr . length - 1 ) {
10
+ function binarySearchRecursive ( arr , x , low = 0 , high = arr . length - 1 ) {
11
11
const mid = Math . floor ( low + ( high - low ) / 2 )
12
12
13
13
if ( high >= low ) {
@@ -18,16 +18,36 @@ function binarySearch (arr, x, low = 0, high = arr.length - 1) {
18
18
19
19
if ( x < arr [ mid ] ) {
20
20
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
21
- return binarySearch ( arr , x , low , mid - 1 )
21
+ return binarySearchRecursive ( arr , x , low , mid - 1 )
22
22
} else {
23
23
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
24
- return binarySearch ( arr , x , mid + 1 , high )
24
+ return binarySearchRecursive ( arr , x , mid + 1 , high )
25
25
}
26
26
} else {
27
27
// if low > high => we have searched the whole array without finding the item
28
28
return - 1
29
29
}
30
30
}
31
+ function binarySearchIterative ( arr , x , low = 0 , high = arr . length - 1 ) {
32
+ while ( high >= low ) {
33
+ const mid = Math . floor ( low + ( high - low ) / 2 )
34
+
35
+ if ( arr [ mid ] === x ) {
36
+ // item found => return its index
37
+ return mid
38
+ }
39
+
40
+ if ( x < arr [ mid ] ) {
41
+ // arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
42
+ high = mid - 1
43
+ } else {
44
+ // arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
45
+ low = mid + 1
46
+ }
47
+ }
48
+ // if low > high => we have searched the whole array without finding the item
49
+ return - 1
50
+ }
31
51
32
52
/* ---------------------------------- Test ---------------------------------- */
33
53
@@ -61,10 +81,10 @@ const stringArr = [
61
81
'Zulu'
62
82
]
63
83
64
- console . log ( binarySearch ( arr , 3 ) )
65
- console . log ( binarySearch ( arr , 7 ) )
66
- console . log ( binarySearch ( arr , 13 ) )
84
+ console . log ( binarySearchRecursive ( arr , 3 ) )
85
+ console . log ( binarySearchIterative ( arr , 7 ) )
86
+ console . log ( binarySearchRecursive ( arr , 13 ) )
67
87
68
- console . log ( binarySearch ( stringArr , 'Charlie' ) )
69
- console . log ( binarySearch ( stringArr , 'Zulu' ) )
70
- console . log ( binarySearch ( stringArr , 'Sierra' ) )
88
+ console . log ( binarySearchIterative ( stringArr , 'Charlie' ) )
89
+ console . log ( binarySearchRecursive ( stringArr , 'Zulu' ) )
90
+ console . log ( binarySearchIterative ( stringArr , 'Sierra' ) )
0 commit comments