如何使二进制搜索更快?

时间:2018-11-04 14:55:45

标签: c# dictionary search binary

我在解决二进制搜索方面遇到了一些问题。任务是通过二进制搜索找到右边界。这段代码可以正常工作,但是问题是它不够快。我该如何处理?

 using System;
 using System.Collections.Generic;

 namespace Autocomplete
 {
public class RightBorderTask
{
    public static int GetRightBorderIndex(IReadOnlyList<string> phrases,
                                           string prefix, int left, int right)
    {
        var middle = (right + left) / 2;
        while (left < right)
        {
            middle = (right + left) / 2;
            if (string.Compare(prefix, phrases[middle],
                               StringComparison.OrdinalIgnoreCase) < 0)
                right = middle;
            else left = middle + 1;
        }
        return (string.Compare(prefix, phrases[left - 1],
                               StringComparison.OrdinalIgnoreCase) 
                               >= 0) ? right : -1;
    }
  }
}

0 个答案:

没有答案