Tuesday, January 01, 2008

Sorting in C# : Is output ideal ??

Array.Sort() in C# is a good and fast way to sort arrays. But here I found a strange problem. Suppose there is two equal values, then ideally it should appear in same order as it was in original array. However this is not the case. To demonstrate this, following class User was created.

public class User :IComparable
{
public string UserName;
public int Age;
public int CompareTo( object obj )
{
User objUser = (User)obj;
return this.Age.CompareTo( objUser.Age );
}
}



Now I created a array of User Datatype and added couple of instance of User to it.

User j = new User();
j.Age = 23;
j.UserName= "anb";

User k = new User();
k.Age = 23;
k.UserName= "any";

User m = new User();
m.Age = 23;
m.UserName= "anr";

User l = new User();
l.Age = 24;
l.UserName= "ana";

User[] arr = new User[]{l,k,m,j};

Now ideally sorting this array using Array.Sort() and printing each element in order should have given following output

Ideal Output
-----------------
anb
any
anr
ana

However it turns out the following output is produced which has the equal elements in a different order.

Actual Output
--------------
anr
anb
any
ana

If I am right, QuickSort is the algorithm that’s used by the Array.Sort function. However, ideally the output should have in order its originally inserted in case of equal elements. I am using 1.1 Framework.