Created
August 1, 2023 20:06
-
-
Save a-alhusaini/92081d493e89de6d6cb228110dadc73b to your computer and use it in GitHub Desktop.
Binary Searching Sorted Array
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
let arr = [] | |
for (let i = 0; i < 12900000; i++) { | |
if (i == 60000000) continue | |
arr.push(i) | |
} | |
function insort(arr, item) { | |
let low = 0; | |
let high = arr.length - 1; | |
while (low < high) { | |
// This is a bitshift operation. It is the equivalent | |
// of Math.floor((low + high) / 2) but faster because | |
// there is no division occurring. | |
let mid = (low + high) >>> 1 | |
if (item < arr[mid]) { | |
high = mid; | |
} else { | |
low = mid + 1; | |
} | |
} | |
arr.splice(low, 0, item) | |
} | |
function slow_insert(arr, item) { | |
if (item < arr[0]) return arr.unshift(item) | |
if (item > arr[arr.length - 1]) return arr.push(item) | |
for (let i = 0; i < arr.length; i++) { | |
if (item > arr[i] && item < arr[i + 1]) { | |
arr.splice(i + 1, 0, item) | |
break | |
} | |
} | |
} | |
console.time("fast") | |
insort(arr, 60000000) | |
console.timeEnd("fast") | |
console.time("slow") | |
slow_insert(arr, 60000000) | |
console.timeEnd("slow") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment