const binarySearch = (arr, x) => {
// Initialise left and right bounds of search to start and end of arr
let left_index = 0;
let right_index = arr.length - 1;
// While left_index and right_index have yet to overlap
while (left_index <= right_index) {
// Find the midpoint between left_index and right_index
let mid_index = Math.floor((left_index + right_index) / 2);
console.log("middle index", mid_index);
// If the element at mid_index is x, return mid_index
// Use Math.floor to ensure that the index position is an integer not a decimal
if (arr[mid_index] === x) {
return mid_index;
}
// Otherwise, if x is greater than elem at mid_index,
// update left_index to be 1 above mid_index
else if (arr[mid_index] < x) {
left_index = mid_index + 1;
}
// Otherwise, if x is less than elem at mid_index,
// update right_index to be 1 below mid_index
else {
right_index = mid_index - 1;
}
}
// If x is not found, return -1
return -1;
};
const myList = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const result = binarySearch(myList, 6); // 4
console.log(result);
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}