Skip to content

Instantly share code, notes, and snippets.

@elitenomad
Created June 20, 2018 11:35
Show Gist options
  • Save elitenomad/ee47e2bb9cdbb253465685f147034971 to your computer and use it in GitHub Desktop.
Save elitenomad/ee47e2bb9cdbb253465685f147034971 to your computer and use it in GitHub Desktop.
Javascript Binary search Implementation
const binary_search = (list, item) => {
let min = 0;
let max = list.length - 1;
let middle_index = Math.floor((min + max)/2);
while(min <= max){
if(list[middle_index] == item) {
return list[middle_index];
}
if(list[middle_index] > item) {
max = middle_index - 1;
}else{
min = middle_index + 1;
}
middle_index = Math.floor((min + max)/2);
if(middle_index == item){
return list[middle_index];
}
}
return -1;
};
const result = binary_search([1,3,5,10,44,434,444,54], 44);
console.log(`what is result ${result}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment