Skip to content

Commit c6a3698

Browse files
committed
Added BinarySearchIterative Function
* BinarySearchIterative Function is added * BinarySearch function is renamed to BinarySearchRecurisve * changes in test function - 3 binarySearchRecursive tests - 3 binarySearchIterative tests
1 parent 87e16d5 commit c6a3698

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

Search/BinarySearch.js

+32-9
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* value is found or the interval is empty.
88
*/
99

10-
function binarySearch (arr, x, low = 0, high = arr.length - 1) {
10+
function binarySearchRecursive (arr, x, low = 0, high = arr.length - 1) {
1111
const mid = Math.floor(low + (high - low) / 2)
1212

1313
if (high >= low) {
@@ -18,17 +18,40 @@ function binarySearch (arr, x, low = 0, high = arr.length - 1) {
1818

1919
if (x < arr[mid]) {
2020
// 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)
2222
} else {
2323
// 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)
2525
}
2626
} else {
2727
// if low > high => we have searched the whole array without finding the item
2828
return -1
2929
}
3030
}
3131

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+
3255
/* ---------------------------------- Test ---------------------------------- */
3356

3457
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@@ -61,10 +84,10 @@ const stringArr = [
6184
'Zulu'
6285
]
6386

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))
6790

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

Comments
 (0)