FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Recursive/BinarySearch.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Recursive
/
BinarySearch.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
33 lines (27 loc) · 1.07 KB
Breadcrumbs
JavaScript
/
Recursive
/
BinarySearch.js
Copy path
File metadata and controls
33 lines (27 loc) · 1.07 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
*
@function
BinarySearch
*
@description
Search the integer inside the sorted integers array using Binary Search Algorithm.
*
@param
{
Integer[]
} arr - sorted array of integers
*
@param
{
Integer
} low - The input integer
*
@param
{
Integer
} high - The input integer
*
@param
{
Integer
} searchValue - The input integer
*
@return
{
Integer
} - return index of searchValue if found else return -1.
*
@see
[BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm)
*/
const
binarySearch
=
(
arr
,
searchValue
,
low
=
0
,
high
=
arr
.
length
-
1
)
=>
{
// base case
if
(
high
<
low
||
arr
.
length
===
0
)
return
-
1
const
mid
=
low
+
Math
.
floor
(
(
high
-
low
)
/
2
)
// If the element is present at the middle
if
(
arr
[
mid
]
===
searchValue
)
{
return
mid
}
// If element is smaller than mid, then
// it can only be present in left subarray
if
(
arr
[
mid
]
>
searchValue
)
{
return
binarySearch
(
arr
,
searchValue
,
low
,
mid
-
1
)
}
// Else the element can only be present in right subarray
return
binarySearch
(
arr
,
searchValue
,
mid
+
1
,
high
)
}
export
{
binarySearch
}
Back
|
FazBrowse Home
|
New Git URL