Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BinarySearch in two dimensional list

Tags:

c#

I have dimensional list:

List<List<string>> index_en_bg = new List<List<string>>();

   index_en_bg.Add(new List<string>() { word1, translation1 }); 
   index_en_bg.Add(new List<string>() { word2, translation2 }); 
   index_en_bg.Add(new List<string>() { word3, translation3 });

I would do binary search by the first column (words), something like this:

int row = index_en_bg.BinarySearch(searchingstr);

but it works only for a one-dimensional list. How would I extend it to work for two-dimensional lists in my case? I don't want to use Dictionary class.

like image 367
vinsa Avatar asked May 28 '13 10:05

vinsa


People also ask

Can you use binary search in a 2D array?

To perform a Binary search in the 2D array, the array needs to be sorted. Here is an unsorted 2D array is given, so applying Binary Search in an unsorted array is not possible. To apply Binary Search first the 2D array needs to be sorted in any order that itself takes (M*N)log(M*N) time.

How many indexes does a two-dimensional list use?

Lists that require two indices to identify an element are called two-dimensional lists (or double-indexed lists or double-subscripted lists).

What is two-dimensional 2D array?

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.


1 Answers

In this case you need to provide your own customer IComparer-implementing comparator

public class Comparer: IComparer<IList<string>>
{
    public int Compare(IList<string> x, IList<string> y)
    {
        // base the comparison result on the first element in the respective lists
        // eg basically
        return x[0].CompareTo(y[0]);
    }

And you'll call it like this, offering a List where only the field you're searching is filled in.

int row = index_en_bg.BinarySearch(new List<string>() {searchingstr},new Comparer());
like image 159
fvu Avatar answered Sep 19 '22 06:09

fvu