DEV Community

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

Posted on

3 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay