Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BinarySearch array of objects by ID

Good day!

I have a List of ValueObj:

class ValueObj
{
   int ID;
   float value;
}

How to get binary search objects by id? (List tempValues)

I make ValueComparer class,but dont know am i right?

class ValueComparer<ValueObj>
{
   public int Compare(ValueObjx, ValueObjy)
   {
       if (x == y) return 0;
       if (x == null) return -1;
       if (y == null) return 1;

       return -1; ///???
   }
}

I need to sort List by ID. Like that?:

tempValues.Sort(new ValueComparer());

And how to use BinarySearch?

like image 360
Admiral Land Avatar asked Oct 20 '22 23:10

Admiral Land


1 Answers

first of all you should make your class like this. your fields were not public and you can not access them, also public fields are not good so you should change them to property

    class ValueObj
    {      
        public int ID { get; set; }
        public float value { get; set; };
    }

and your comparer like this

class ValueComparer : IComparable<ValueObj>
{
  public int Compare(ValueObj x, ValueObj y)
  {
      if (ReferenceEquals(x, y)) return 0;
      if (x == null) return -1;
      if (y == null) return 1;

      return x.ID == y.ID ? 0 :
               x.ID > y.ID ? 1 : -1;
  }
}

then you have a list like

var tempValues = new List<ValueObj>();
//many items are added here

you should always sort your list before performing a binary serach

 //this does not modify the tempValues and generate a new sorted list
 var sortedList = tempValues.OrderBy(x => x.ID).ToList();

or you can sort tempValues directly

//tempValues is modified in this method and order of items get changed
tempValues.Sort(new ValueComparer<ValueObj>());

now you want to find index of specific ValueObj

var index = sortedList.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());

or if you have used second method of sorting

var index = tempValues.BinarySearch(specificValueObj, new ValueComparer<ValueObj>());
like image 180
Hamid Pourjam Avatar answered Oct 27 '22 00:10

Hamid Pourjam