File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Binary search is an efficient algorithm for finding an item from a sorted list of items.
3+ * It works by repeatedly dividing in half the portion of the list that could contain the item,
4+ * until you've narrowed down the possible locations to just one.
5+ */
6+
7+ function binarySearch ( arr , x , left , right ) {
8+ if ( left > right ) {
9+ return false ;
10+ }
11+
12+ const middle = Math . floor ( left + ( right - left ) / 2 ) ;
13+ if ( arr [ middle ] === x ) {
14+ return true ;
15+ } else if ( x < arr [ middle ] ) {
16+ return binarySearch ( arr , x , left , middle - 1 ) ;
17+ } else {
18+ return binarySearch ( arr , x , middle + 1 , right ) ;
19+ }
20+ }
21+
22+ export default function ( arr , x ) {
23+ return binarySearch ( arr , x , 0 , arr . length ) ;
24+ }
You can’t perform that action at this time.
0 commit comments