Is the sorting algorithm used by .NET's `Array.Sort()` method a stable algorithm?

前端 未结 5 1139
灰色年华
灰色年华 2020-11-29 07:44

Is the sorting algorithm used by .NET\'s Array.Sort() method a stable algorithm?

5条回答
  •  天命终不由人
    2020-11-29 08:19

    UPDATE: This code not stabilizing Array.Sort (ensure that the elements are always sorted in the same order):

    public static class ComparisonExtensions
    {
        public static Comparison WithGetHashCode(this Comparison current)
        {
            return (x, y) =>
            {
                var result = current(x, y);
                if (result == 0)
                    return x.GetHashCode() - y.GetHashCode();
                return result;
            };
        }
    }
    

    Use:

    Comparison comparison = (x, y) => x.BirthYear.CompareTo(y.BirthYear);
    Array.Sort(unstable, comparison.WithGetHashCode());
    

提交回复
热议问题