The ordering of the original position of the equal element is called solid. An unstable sort does not guarantee that elements of equality remain in their original order after they are sorted.
. NET uses the sort method that is not stable. These sorting methods, including System.Array.Sort and System.collections.generic.list<t> Sort, which uses a quick sort algorithm, which is relatively fast.
However, there will always be times when you need a solid sort, at which point a solution is required.
Example:
Using an example can be a good illustration of a solid sort. Consider the following person class, which contains the name and age two attributes, and also implements the IComparable interface (which contains the CompareTo method). The CompareTo method here is sorted according to age.
class Person : IComparable
{
public Person( string name, int age )
{
this.Name = name;
this.Age = age;
}
public string Name;
public int Age;
public int CompareTo( object obj )
{
int result = 1;
if (obj != null && obj is Person)
{
Person person = (Person)obj;
result = this.Age.CompareTo( person.Age );
}
return result;
}
public override string ToString()
{
return String.Format( "{0} - {1}", this.Name, this.Age );
}
}
Now, let's create, sort, and write a collection of person classes.
Person p1 = new Person( "Abby", 38 );
Person p2 = new Person( "Bob", 23 );
Person p3 = new Person( "Charlie", 23 );
Person p4 = new Person( "Danielle", 18 );
List<Person> list = new List<Person>();
list.Add( p1 );
list.Add( p2 );
list.Add( p3 );
list.Add( p4 );
list.Sort();
Console.WriteLine( "Unstable List Sort:" );
foreach (Person p in list)
{
Console.WriteLine( p );
}