Novice Developer
Novice Developer

Reputation: 4749

How CompareTo method logic works in List sort function?

How CompareTo method logic works in List sort function.

public class person : IComparable
{
    string firstName;
    string lastName;

    public int CompareTo(object obj)
    {
        person otherPerson = (person)obj;
        if (this.lastName != otherPerson.lastName)
            return this.lastName.CompareTo(otherPerson.lastName);
        else
            return this.firstName.CompareTo(otherPerson.firstName);
    }

    public person(string _firstName, string _lastName)
    {
        firstName = _firstName;
        lastName = _lastName;
    }

    override public string ToString()
    {
        return firstName + " " + lastName;
    }
}

List<person> l = new List<person>();
l.Add(new person("Mark", "Hanson"));
l.Add(new person("Kim", "Akers"));
l.Add(new person("Zsolt", "Ambrus"));

l.Sort();

foreach (person p in l)
    Console.WriteLine(p.ToString());

Upvotes: 1

Views: 7866

Answers (2)

Mike Dinescu
Mike Dinescu

Reputation: 55720

When you invoke the Sort method on a generic list (List in your case), behind the scenes, the implementation of Sort will check if the type of the list (the person class) implements the IComparable interface, and if it does it will invoke the CompareTo member to perform comparisons between elements of the list to perform the sort. The fact that the person class implements IComparable is interpreted as a "contract" that specifies that the person class will have a method called CompareTo.

The implementation of Sort can use a snippet such as the following to compare to elements of the list:

T aPerson;
T anotherPerson;
int compareResult;

if(aPerson is IComparable)
{
    compareResult = (aPerson as IComparable).CompareTo(anotherPerson);
}

The CompareTo method always compares the object it is invoked on to the parameter and the meaning of the return value is always the same:

* if the two objects are "equal", it returns 0
* if the object you are comparing to is "less than" - in a sorted list it goes before - the object you are invoking CompareTo on, it returns -1
* if the object you are comparing to is "greater than" - in a sorted list it goes after - the object you are invoking CompareTo on, it returns +1

Internally, the Sort method uses an optimized QuickSort to actually perform the sort but to make it easier to follow, here's an example of implementing bubble sort which illustrates what happens behind the scenes in terms of invoking the IComparable interface:

// assume the Sort invokes this naive bubble sort 
// on the internal backing array of the list
void InternalBubbleSort(T[] backingArray) 
{
  var swapped = false;
  do {
    swapped = false;
    for(int i = 0; i < Length - 1; i++) {
      if (backingArray[i].CompareTo(backingArray[i+1]) > 0) {
        T temp = backingArray[i];
        backingArray[i] = backingArray[i+1];
        backingArray[i+1] = temp;
        swapped = true;
      }
    }while(swapped);
}

Upvotes: 4

SLaks
SLaks

Reputation: 887375

It sorts by last name, then first name.

If two people have the same last name, the if statement will end up comparing by first name.
Otherwise, it will compare by last name.

Upvotes: 2

Related Questions