Skip to content

Instantly share code, notes, and snippets.

@kostandy
Created January 11, 2021 11:46
Show Gist options
  • Save kostandy/1cefcb20d93cc18dca5eaa7b1ef926ae to your computer and use it in GitHub Desktop.
Save kostandy/1cefcb20d93cc18dca5eaa7b1ef926ae to your computer and use it in GitHub Desktop.
The binary search algorithm realization with randomized array generation & performance measurements tracking
const binarySearch = (list = [1, 2, 3, 4, 5, 6, 7, 8, 9], searchableValue = 4) => {
let low = 0,
high = list.length - 1;
while (low <= high) {
let middle = Math.floor(low + (high - low) / 2);
if (list[middle] < searchableValue) {
low = middle + 1;
} else if (list[middle] > searchableValue) {
high = middle - 1;
} else if (list[middle] === searchableValue) {
return middle;
}
}
return -1;
}
const randomArray = (length, max) => [...Array(length)].map(e=>~~(Math.random()*max));
const t0 = performance.now();
console.log(binarySearch(randomArray(10000, 30).sort((a, b) => a - b), ~~(Math.random()*10)));
const t1 = performance.now();
console.log("Call to binarySearch took " + (t1 - t0) + " milliseconds.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment