Skip to content

Instantly share code, notes, and snippets.

@zacacollier
Created February 27, 2017 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacacollier/35322832180c9c005e7dc494b63433cf to your computer and use it in GitHub Desktop.
Save zacacollier/35322832180c9c005e7dc494b63433cf to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/rofipeh
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
function binarySearch (seq, t) {
while (seq.length) {
let m = Math.floor(seq.length / 2)
if (seq[m] === t) {
return `target is ${seq[m]}`
}
else if (seq[m] < t) {
seq = seq.slice(m + 1)
console.log(`hit less than, seq is ${seq}`)
}
else {
seq = seq.slice(0, m)
console.log(`hit else, m is ${m} seq is ${seq}`)
}
}
return null
}
let array = [0, 1, 4, 5, 56, 68, 99]
//console.log(binarySearch(array, 86))
console.log(binarySearch(array, 4))
</script>
<script id="jsbin-source-javascript" type="text/javascript">function binarySearch (seq, t) {
while (seq.length) {
let m = Math.floor(seq.length / 2)
if (seq[m] === t) {
return `target is ${seq[m]}`
}
else if (seq[m] < t) {
seq = seq.slice(m + 1)
console.log(`hit less than, seq is ${seq}`)
}
else {
seq = seq.slice(0, m)
console.log(`hit else, m is ${m} seq is ${seq}`)
}
}
return null
}
let array = [0, 1, 4, 5, 56, 68, 99]
//console.log(binarySearch(array, 86))
console.log(binarySearch(array, 4))</script></body>
</html>
function binarySearch (seq, t) {
while (seq.length) {
let m = Math.floor(seq.length / 2)
if (seq[m] === t) {
return `target is ${seq[m]}`
}
else if (seq[m] < t) {
seq = seq.slice(m + 1)
console.log(`hit less than, seq is ${seq}`)
}
else {
seq = seq.slice(0, m)
console.log(`hit else, m is ${m} seq is ${seq}`)
}
}
return null
}
let array = [0, 1, 4, 5, 56, 68, 99]
//console.log(binarySearch(array, 86))
console.log(binarySearch(array, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment