簡體   English   中英

二進制搜索多維數組中的第一個元素

[英]Binary Search on the first element in a multiple dimensional array

我的目標是僅對二維數組中的第一個元素執行二進制搜索。 我一整天都在尋找是否有可能在.NET中使用BinarySearch()但我找不到東西。

為了使這更清楚。 想象一下,我有一個1D數組,未分類。 如果我對數組進行排序,則會丟失原始索引。 我想創建我的數組的第二個元素來保存原始索引(我可以做)然后按第一個元素排序,然后對第一個元素進行二元搜索。

如果有人能把我推向正確的方向,我將非常感激。 謝謝

好吧,如果我理解正確,你需要這樣的東西:

// 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

根據MSDNArray.BinarySearch方法僅對一維數組進行操作,因此在您的情況下不可能直接使用它。 您擁有的一些選項是:

  1. 將第一列提取到單獨的數組中並在其上調用Array.BinarySearch
  2. 定義實現接口IComparable自定義類Pair,並使用此類的實例構造數組。
  3. 自己在二維數組上實現二進制搜索。

看起來你想擁有保存數據和“原始索引”的對象,而不是按數據排序/搜索對象數組。

(這個答案顯示了Andrei的選擇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以獲取實現/使用詳細信息。

根據您之后計划對陣列執行的操作,另一種解決方案可能是使用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倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM