Created
March 29, 2019 15:22
-
-
Save aadebdeb/964ff754d4045e2b7b1fea8044e7420d to your computer and use it in GitHub Desktop.
binary search to find index range from array with duplicated values in JavaScript
This file contains 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
function binarysearchMinIndex(array, target, from, to) { | |
while (from !== to) { | |
const middle = from + Math.floor((to - from) / 2); | |
if (array[middle] < target) { | |
from = middle + 1; | |
} else { | |
to = middle; | |
} | |
} | |
if (array[from] === target) { | |
return from; | |
} else { | |
return -1; | |
} | |
} | |
function binarysearchMaxIndex(array, target, from, to) { | |
while (from !== to) { | |
const middle = from + Math.ceil((to - from) / 2); | |
if (array[middle] > target) { | |
to = middle - 1; | |
} else { | |
from = middle; | |
} | |
} | |
if (array[from] === target) { | |
return from; | |
} else { | |
return -1; | |
} | |
} | |
function binarysearchRange(array, target) { | |
const from = binarysearchMinIndex(array, target, 0, array.length - 1); | |
const to = from !== -1 ? binarysearchMaxIndex(array, target, from, array.length - 1) : -1; | |
return { from: from, to: to }; | |
} | |
function linearsearch(array, target) { | |
let from = -1; | |
let to = -1; | |
for (let i = 0; i < array.length; i++) { | |
if (array[i] === target) { | |
from = i; | |
break; | |
} | |
} | |
for (let i = array.length - 1; i >= 0; i--) { | |
if (array[i] === target) { | |
to = i; | |
break; | |
} | |
} | |
return { from: from, to: to }; | |
} | |
// test | |
const array = Array.from({length: 512}, () => { | |
return Math.floor(Math.random() * 64.0); | |
}).sort((a, b) => a < b ? -1 : a > b ? 1 : 0); | |
for (let i = -100; i < 100; i++) { | |
const actual = binarysearchRange(array, i); | |
const expected = linearsearch(array, i); | |
if (actual.from !== expected.from || actual.to !== expected.to) { | |
console.error('not correct'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ordinary binary search