I know there are a ton of binary search examples, but I'm having difficulty getting any to work when I have a sorted array of numbered strings, for example.
const sortedStringNumbers = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
When I plug it into a binary search function like this:
function bsearch (Arr,value){
var low = 0 , high = Arr.length -1 ,mid ;
while (low <= high){
mid = Math.floor((low+high)/2);
if(Arr[mid]==value) return true;
else if (Arr[mid]<value) low = mid+1;
else high = mid-1;
}
return -1 ;
}
When I run:
bsearch(sortedStringNumbers, '3')
it returns -1
When I run :
bsearch(sortedStringNumbers, '26)
it returns true;
Lastly, the reason I simply don't convert the binary search input array is I need to use this function for two kinds of sorted arrays, the aforementioned kind, and others that contain words, such as: const sortedWordsArray = ['Algebra', 'Biology', 'Chemistry', ...]
The binary search array does work for word arrays, btw.