简体   繁体   English

数字字符串的二进制搜索数组未找到值

[英]Binary Search array of number strings not finding values

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它返回-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', ...]最后,我根本不转换二进制搜索输入数组的原因是我需要将此函数用于两种排序数组,上述类型和其他包含单词的数组,例如: const sortedWordsArray = ['Algebra', 'Biology', 'Chemistry', ...]

The binary search array does work for word arrays, btw.二进制搜索数组确实适用于单词数组,顺便说一句。

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 ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM