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,17 +18,40 @@ 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
31
32
+ function binarySearchIterative ( arr , x , low = 0 , high = arr . length - 1 ) {
33
+
34
+ while ( high >= low ) {
35
+ const mid = Math . floor ( low + ( high - low ) / 2 )
36
+
37
+ if ( arr [ mid ] === x ) {
38
+ // item found => return its index
39
+ return mid
40
+ }
41
+
42
+ if ( x < arr [ mid ] ) {
43
+ // arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
44
+ high = mid - 1
45
+ } else {
46
+ // arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
47
+ low = mid + 1
48
+ }
49
+ }
50
+ // if low > high => we have searched the whole array without finding the item
51
+ return - 1
52
+ }
53
+
54
+
32
55
/* ---------------------------------- Test ---------------------------------- */
33
56
34
57
const arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
@@ -61,10 +84,10 @@ const stringArr = [
61
84
'Zulu'
62
85
]
63
86
64
- console . log ( binarySearch ( arr , 3 ) )
65
- console . log ( binarySearch ( arr , 7 ) )
66
- console . log ( binarySearch ( arr , 13 ) )
87
+ console . log ( binarySearchRecursive ( arr , 3 ) )
88
+ console . log ( binarySearchIterative ( arr , 7 ) )
89
+ console . log ( binarySearchRecursive ( arr , 13 ) )
67
90
68
- console . log ( binarySearch ( stringArr , 'Charlie' ) )
69
- console . log ( binarySearch ( stringArr , 'Zulu' ) )
70
- console . log ( binarySearch ( stringArr , 'Sierra' ) )
91
+ console . log ( binarySearchIterative ( stringArr , 'Charlie' ) )
92
+ console . log ( binarySearchRecursive ( stringArr , 'Zulu' ) )
93
+ console . log ( binarySearchIterative ( stringArr , 'Sierra' ) )
0 commit comments