0

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.

1
  • 3
    Your "sorted" numbers are not sorted. They're strings, so they need to be sorted lexically, not numerically. Commented Feb 20, 2020 at 22:15

1 Answer 1

1

Check to make sure your array is sorted.

When you're making your comparison

Arr[mid]<value

or

Arr[mid]==value

They are being compared as strings rather than as numeric values.

If you'd like it to work in "both" scenarios, as you suggested, you could try something like this

function bsearch (Arr,value){
        var low  = 0 , high = Arr.length -1 ,mid ;      
        while (low <= high){
            mid = Math.floor((low+high)/2);     

            var int_val = Arr[mid];
            if (!isNaN(Arr[mid])) {
                int_val = parseInt(Arr[mid]);
            }

            if(int_val==value) { 
                return true; 
            }
            else if (int_val<value) {
                low = mid+1;
            }
            else {
                high = mid-1;          
            }
        }
        return -1 ;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.