Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created June 14, 2019 02:14
Show Gist options
  • Save jasonwaters/6313364f1c4d5a136d4d5343820a84eb to your computer and use it in GitHub Desktop.
Save jasonwaters/6313364f1c4d5a136d4d5343820a84eb to your computer and use it in GitHub Desktop.
insert elements into an array, keeping it sorted.
function binarySearch(arr, target, left, right, closest=-1) {
if(arr.length <=0) return 0;
const mid = Math.floor((left+right)/2);
closest = arr[mid] < target ? mid+1 : mid;
if(left < right) {
if(arr[mid] < target) {
return binarySearch(arr, target, mid+1, right, closest);
}else if(arr[mid] > target) {
return binarySearch(arr, target, left, mid-1, closest);
}
}
return closest;
}
function findValue(haystack, needle) {
return binarySearch(haystack, needle, 0, haystack.length);
}
function insertValue(arr, value) {
const idx = findValue(arr, value);
arr.splice(idx,0,value);
return arr;
}
let arr = [];
[3,6,1, 0, 10, 9, 4, -1, -5, 20, 19, 4, 3, 2, 7].forEach(value => {
insertValue(arr, value);
console.log(arr);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment