Skip to main content
 首页 » 编程设计

c#之对多维数组中的第一个元素进行二进制搜索

2024年02月20日14jyk

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

为了更清楚地说明这一点。假设我有一个未排序的一维数组。如果我对数组进行排序,我将丢失原始索引。我想创建我的数组的第二个元素来保存原始索引(我可以这样做)然后按第一个元素排序,然后对第一个元素进行二进制搜索。

如果有人能将我推向正确的方向,我将不胜感激。 谢谢

请您参考如下方法:

好吧,如果我没理解错的话,你需要这样的东西:

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