Binary search in simple phrase.
Abhay Prajapati
Posted on March 21, 2022
binary search is something which divides something in half every time it fail's.
as if the search failed to find any thing then if divide's its array into half and and half and half.
unless it finds the value or array becomes zero.
//visiable presentation.
// random array
let array = [1, 2,3,4,5,6,7,8]
// let's make binary function which take and arrays and target to it's value.
const binary_search_function = (array
, target
){
//as we have to check find starting to ending of array.
//we start with 0 and this end of array
let start = 0
// as array will start from 0 and length function also count's 0 as 1 so we divide it' by 1
let end = array
.length - 1
//this will count middle of array.
let middle = (start+end)/2
while(array
[middle] !== target && start<=end){
if(target< array
[middle]) {
end = middle -1
} else {
start = middle +1
}
middle = (start+end)/2
}
return array[middle] === target ? 'found at index ${middle}-> ${target}'
: "not found"
}
console.log(binary_search_function(array, 12)
//found at 9-> 12
console.log(binary_search_function(array, 123)
// not found
Posted on March 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 25, 2024