Binary Search

Run Settings
LanguageJavaScript
Language Version
Run Command
/* Returns either the index of the location in the array, or -1 if the array did not contain the targetValue */ 'use strict'; const doSearch = (array, targetValue) => { let min = 0; let max = array.length - 1; let guess; while (min <= max) { guess = (min + max) / 2 | 0; if (array[guess] > targetValue) { max = guess - 1; } else if (array[guess] < targetValue) { min = guess + 1; } else { return guess; } } return -1; }; const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]; const result = doSearch(primes, 61); console.log(`Found prime at index ${result}`);
Editor Settings
Theme
Key bindings
Full width
Lines