首页 文章

二进制搜索多维数组中的第一个元素

提问于
浏览
1

我的目标是仅对二维数组中的第一个元素执行二进制搜索 . 我一整天都在寻找是否有可能在.NET中使用BinarySearch(),但我找不到任何东西 .

为了使这更清楚 . 想象一下,我有一个1D数组,未分类 . 如果我对数组进行排序,则会丢失原始索引 . 我想创建我的数组的第二个元素来保存原始索引(我可以做)然后按第一个元素排序,然后对第一个元素进行二元搜索 .

如果有人能把我推向正确的方向,我将非常感激 . 谢谢

4 回答

  • 0

    好吧,如果我理解正确,你需要这样的东西:

    // initialize the array and the indexes array
    var a2D = new int[2][];
    a2D[0] = new[] { 3, 14, 15, 92, 65, 35 }; // <-- your array (fake data here)
    a2D[1] = Enumerable.Range(0, a2D[0].Length).ToArray(); // create the indexes row
    
    // sort the first row and the second one containing the indexes
    Array.Sort(a2D[0], a2D[1]);
    
    // now a2D array contains:
    //  row 0: 3, 14, 15, 35, 65, 92
    //  row 1: 0,  1,  2,  5,  4,  3
    
    // and you can perform binary search on the first row:
    int columnIndexOf35 = Array.BinarySearch(a2D[0], 35);
    // columnIndexOf35 = 3
    // 
    // a2D[0][columnIndexOf35] = 35 <- value
    // a2D[1][columnIndexOf35] = 5  <- original index
    
  • 3

    根据MSDNArray.BinarySearch 方法仅对一维数组进行操作,因此在您的情况下不可能直接使用它 . 您拥有的一些选项是:

    • 将第一列提取到单独的数组中并在其上调用 Array.BinarySearch .

    • 定义实现接口 IComparable 的自定义类Pair,并使用此类的实例构造数组 .

    • 自己在二维数组上实现二进制搜索 .

  • 0

    看起来你想拥有保存数据和“原始索引”的对象,而不是按数据排序/搜索对象数组 .

    (这个答案显示了安德烈的选择2)

    class IndexedData:IComparable
    {
      public MyType Data;
      public int OriginalIndex;
    
      public int CompareTo(object obj) {
        // add correct checks for null,.. here
        // and return correct comparison result. 
        // I.e. if MyType is IComparable - just delegate.
        return Data.CompareTo(obj);
    }
    

    检查MSDN上的IComparable以获取实施/使用详细信息 .

  • 1

    根据您之后计划对阵列执行的操作,另一种解决方案可能是使用LINQ .

    var unsortedStartingArray = new[] {3, 6, 2, 1, 20, 20};
    var q = unsortedStartingArray
            .Select((item, index) => new {item, index})
            .ToLookup(x => x.item, x => x.index);
    
    var notFound = q[30]; // An empty array. Nothing found
    var indexOf1 = q[1].First(); // returns 3
    var multipleIndexsOf20 = q[20]; // Returns an array with 4, 5
    

    然后,查找的索引将是您要搜索的值 . 性能方面,我认为这比我的原油测试速度要快5倍 .

相关问题