Quick actions

cmd+k|ctrl+k

Navigation

Languages

Binary Search

Snippet info

Language

JavaScript

Visibility

public

Author

christian.lohr

Created

2016-05-01T18:23:30Z

Updated

2016-05-03T02:08:17Z

/* 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}`);
INFO