Binary Search Implementation in JavaScript

Level 5421 keystrokes

binarySearch finds a value in a sorted array by checking the middle element and halving the range each step. It prints 3 for 7, -1 for 8 (not present) and 0 for 1.

JavaScript code

// Returns the index of target in the sorted array arr, or -1
1function binarySearch(arr, target) {
// The search range starts as the whole array: indexes 0 to length - 1
2 let left = 0;
3 let right = arr.length - 1;
4
// Loops while the range still contains at least one element
5 while (left <= right) {
// Index of the middle element, rounded down
6 const mid = Math.floor((left + right) / 2);
7
// The middle element is the target: returns its index
8 if (arr[mid] === target) return mid;
// The middle is too small, so the target can only be in the right half
9 if (arr[mid] < target) left = mid + 1;
// The middle is too large, so the search continues in the left half
10 else right = mid - 1;
11 }
12
// The range became empty: the target is not in the array
13 return -1;
14}
15
// Binary search only works on a sorted array like this one
16const sorted = [1, 3, 5, 7, 9, 11, 13, 15];
// 7 is found at the first middle, index 3, so this prints 3
17console.log(binarySearch(sorted, 7));
// 8 is not in the array, so this prints -1
18console.log(binarySearch(sorted, 8));
// 1 is the first element, so this prints 0
19console.log(binarySearch(sorted, 1));

Output

3
-1
0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 12
  • )× 12
  • ,× 11
  • ;× 11
  • =× 10
  • .× 5
  • -× 3
  • [× 3
  • ]× 3
  • {× 2

More JavaScript examples at level 5

← JavaScript typing practice