Created
June 20, 2018 11:35
-
-
Save elitenomad/ee47e2bb9cdbb253465685f147034971 to your computer and use it in GitHub Desktop.
Javascript Binary search Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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