Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search on List<Tuple<int,int>> in c#

Tags:

c#

list

search

I use C# language and I have a little question about List<Tuple<int,int>>. Assume that I created a List<Tuple<int,int>> and then inserted some entry to it like: (12,3),(154,43),(85,342)

Now I want to search the List JUST by first item, i.e. just by item1 and I want to do this by binary search.

something like this:

List<Tuple<int,int>> tt = new List<Tuple<int,int>>();
tt.Add(new Tuple<int,int>(12,32));
tt.sort();
tt.binarysearch(item1:12);

and some output like this:

12 32

Now is there any solution?

like image 269
Chavoosh Avatar asked Dec 13 '13 12:12

Chavoosh


1 Answers

Yes, BinarySearch takes IComparer, and you can create your own custom comparer that inherits from IComparer<Tuple<int, int>>

As such:

public class BinarySearchComparer : IComparer<Tuple<int, int>>
{
    public int Compare(Tuple<int, int> f1, Tuple<int, int> f2)
    {
        return Comparer<int>.Default.Compare(f1.Item1, f2.Item1);
    }
}

and example:

tt.Binarysearch(12, new BinarySearchComparer());

See more for information: http://msdn.microsoft.com/en-us/library/ftfdbfx6(v=vs.110).aspx

like image 114
Erti-Chris Eelmaa Avatar answered Sep 26 '22 02:09

Erti-Chris Eelmaa