DEV Community

Cover image for Binary search in simple phrase.
Abhay Prajapati
Abhay Prajapati

Posted on

Binary search in simple phrase.

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.
Binary search reprentation
// 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

connect on twitter

Top comments (0)