Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether List<T>.Sort actually sorted something?

Tags:

c#

.net

sorting

Consider the following code:

class Employee : IComparable<Employee>
{
    public string Name { get; set; }

    public int CompareTo(Employee other)
    {
        return string.Compare(this.Name, other.Name);
    }
}

void DoStuff()
{
    var e1 = new Employee() { Name = "Frank" };
    var e2 = new Employee() { Name = "Rizzo" };

    var lst = new List<Employee>() { e1, e2 };
    lst.Sort();
}

How do I know if the Sort method actually rearranged anything? Bonus question: if it rearrange, how many things?

like image 404
AngryHacker Avatar asked Jan 14 '23 01:01

AngryHacker


2 Answers

Taken from http://msdn.microsoft.com/en-us/library/bb348567.aspx You'd have to make a copy of the list before you sort it to compare it to, though.

List<Pet> pets1 = new List<Pet> { pet1, pet2 };
List<Pet> pets2 = new List<Pet> { pet1, pet2 };

bool equal = pets1.SequenceEqual(pets2);
like image 133
Tim Avatar answered Jan 18 '23 23:01

Tim


Since you have implemented your own comparer, why not track how many times it is called?

// naive, not thread safe, not exactly going to tell you much
static int compared = 0;
public int CompareTo(Employee other)
{
    compared++;
    return string.Compare(this.Name, other.Name);
}

As another approach, why not switch to sorted input rather than sorting the entire list each time?

public void AddEmployee(Employee item)
{
    // keep in mind this may not always be faster than List<T>.Sort
    // but it should be.
    if (employees.Count > 1)
    {
        var index = employees.BinarySearch(item);
        if (index < 0)
        {
            employees.Insert(~index, item);
        }
    }
    else employees.Add(item);
}

Alternatively, use a sorted collection like SortedList<K,T>.

like image 21
user7116 Avatar answered Jan 18 '23 23:01

user7116