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 -11function binarySearch(arr, target) { // The search range starts as the whole array: indexes 0 to length - 12 let left = 0;3 let right = arr.length - 1;4 // Loops while the range still contains at least one element5 while (left <= right) { // Index of the middle element, rounded down6 const mid = Math.floor((left + right) / 2);7 // The middle element is the target: returns its index8 if (arr[mid] === target) return mid; // The middle is too small, so the target can only be in the right half9 if (arr[mid] < target) left = mid + 1; // The middle is too large, so the search continues in the left half10 else right = mid - 1;11 }12 // The range became empty: the target is not in the array13 return -1;14}15 // Binary search only works on a sorted array like this one16const sorted = [1, 3, 5, 7, 9, 11, 13, 15];// 7 is found at the first middle, index 3, so this prints 317console.log(binarySearch(sorted, 7));// 8 is not in the array, so this prints -118console.log(binarySearch(sorted, 8));// 1 is the first element, so this prints 019console.log(binarySearch(sorted, 1));Output
3 -1 0
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