Is this an efficient way of finding the minimum using binary search?
//Find the minimum in a sorted rotated list of numbers
function findmin(arr, low, high){
if(low==high)
return arr[low];
if(arr[low]<arr[high])
return arr[low];
if((high-low) == 1)
return Math.min(arr[high], arr[low]);
var mid = Math.floor((low+high)/2);
//search right side
if(arr[mid] >= arr[low]){
return findmin(arr, mid+1, high);
}
else{
return findmin(arr, low, mid);
}
}
var arr = [8,8,8,8,8,1];
console.log(findmin(arr, 0, arr.length-1));
Math.min
. – Joseph the Dreamer Jan 10 at 5:09if(arr[low]<arr[high])
, which shouldn't happen when sorted desc like in your example. 3) Using other values inarr
gives weird results, such as[9,8,8,8,8,1]
giving8
,[8,8,8,8,6,1]
giving 6, or[8,8,8,8,1,0]
giving1
. – cFreed Jan 10 at 17:20if(arr[low]<arr[high]) return [whatever]
looks wrong - please elaborate on sorted rotated array. Is there a javascript convention whetherhigh
is inclusive or exclusive? I'd test for "2 elements, at most" first. – greybeard Jan 11 at 8:41