Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This question already has an answer here:

(这个问题在这里已有答案:)

I am trying to optimize a function which does binary search of strings in JavaScript.

(我正在尝试优化一个在JavaScript中对字符串进行二进制搜索的函数。)

Binary search requires you to know whether the key is == the pivot or < the pivot.

(二进制搜索要求您知道密钥是==枢轴还是<枢轴。)

But this requires two string comparisons in JavaScript, unlike in C like languages which have the strcmp() function that returns three values (-1, 0, +1) for (less than, equal, greater than).

(但这需要在JavaScript中进行两次字符串比较,这与C语言类似,后者的strcmp()函数返回三个值(-1, 0, +1) (小于,等于,大于)。)

Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search?

(JavaScript中是否存在这样的本机函数,它可以返回三元值,以便在二进制搜索的每次迭代中只需要进行一次比较?)

  ask by HRJ translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
422 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the localeCompare() method.

(您可以使用localeCompare()方法。)

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

(进一步阅读:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...