Skip to content

Instantly share code, notes, and snippets.

@ValentynaGorbachenko
Created October 12, 2016 22:11
Show Gist options
  • Save ValentynaGorbachenko/fcb593f80469452ccac19c3b4e4f786f to your computer and use it in GitHub Desktop.
Save ValentynaGorbachenko/fcb593f80469452ccac19c3b4e4f786f to your computer and use it in GitHub Desktop.
binary_search created by ValentynaGorbachenko - https://repl.it/C74Z/12
// O(log(n)) - time complexity
// O(n) - space complexity
function binarySearch(arr,val){
if (arr.length === 0){return -1;}
var li = 0;
var hi = arr.length-1;
while(li<=hi){
var mid = Math.floor(li+(hi-li)/2);
// console.log(li, mid, hi);
if (arr[mid] === val){
return mid;
}else if (arr[mid]<val) {
li = mid+1;
} else if (arr[mid]>val){
hi = mid-1;
}
}
return -1;
}
var arr = [0,1,3,5,9,12,20];
console.log("array [0,1,3,5,9,12,20] has 12 in position ",binarySearch(arr, 12));
function binarySearchRecursively(arr, val, li, hi){
if(!arr.length) {return -1;}
if (li === undefined && hi === undefined){
li = 0;
hi = arr.length -1;
}
if (li<=hi) {
var mid = Math.floor(li+(hi-li)/2);
// var mid = Math.floor((hi+li)/2);
// console.log(li, mid, hi);
if ( arr[mid] == val) {return mid;}
if(arr[mid]> val){
return binarySearchRecursively(arr, val, li, mid-1);
}
return binarySearchRecursively(arr, val, mid+1, hi);
}
return -1;
}
var arr2 = [0,1,3,5,9,12,20];
console.log("array 2 [0,1,3,5,9,12,20] has 1 in position ",binarySearchRecursively(arr2, 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment