C # Stable sort (firm sort)

Source: Internet
Author: User
Tags sort

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 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.