简体   繁体   English

你能在 javascript 中的字符串数组中进行二进制搜索吗

[英]Can you do binary search in array of strings in javascript

I am trying to make a word look up thing.我正在尝试查找单词。 Problem there are thousands of words.问题有几千字。 It would be nice to this:这样做会很好:

Search for first letter only, character at index 0, in array, get the index of key/value the ones which have and than search for, character at index 1, and so on.仅搜索第一个字母,索引 0 处的字符,在数组中,获取具有而不是搜索的键/值的索引,索引 1 处的字符,依此类推。

what i don't want to do if possible...如果可能的话,我不想做的事......

Go to array[i], take its whole value, than find char at index 0, than say yes it is this or not. Go 到 array[i],取它的整个值,然后在索引 0 处找到 char,然后说是或不是。 That kind beats the whole point.那种胜过重点。 If am accessing the whole string so why not just evaluate the whole thing while at it.如果我正在访问整个字符串,那么为什么不直接评估整个字符串呢?

Maybe i need to restructure the array somewhat differently.也许我需要以不同的方式重组数组。 so main array would be like `var a = [a,b,c,...] then a[a]=[a,b,c,d,e,...] then so on eventually a[i][r][p][l][a][n][e]... maybe this is more efficient.所以主数组就像 `var a = [a,b,c,...] 然后 a[a]=[a,b,c,d,e,...] 最后 a[i] [r][p][l][a][n][e]...也许这样更有效率。 It might be the only way possible if i can't access value's only first char in array without first taking in the whole thing than analyzing.如果我在不首先考虑整个事情而不是分析的情况下无法访问数组中值的唯一第一个字符,这可能是唯一可能的方法。

I think you can do it. 我想你能做到。 You just have to sort the string array and maybe you can compare them with the char value for instance 65 for A. 您只需要对字符串数组进行排序,也许可以将它们与A的实例65的char值进行比较。

I have not testet it, but this seems legit: http://www.dweebd.com/javascript/binary-search-an-array-in-javascript/ 我还没有做过测试,但这似乎是合法的: http ://www.dweebd.com/javascript/binary-search-an-array-in-javascript/

Maybe I don't understand what you are trying to do, but if you can keep your word list sorted, then binary search is the quickest and most efficient way to do it:也许我不明白你想做什么,但如果你能保持你的单词列表排序,那么二进制搜索是最快和最有效的方法:

function binarySearch(list, key) {
    let indexLow = 0;
    let indexHigh = list.length - 1;
    while (indexLow <= indexHigh) {
        const mid = Math.floor((indexLow + indexHigh) / 2)
        const x = list[mid]
        if (x === key) {
            return mid;
        }
        if (x > key) {
            indexHigh = mid - 1;
        } else {
            indexLow = mid + 1;
        }
    }
    return -1;
}

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

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