开发者

Generic BubbleSort Extension

    publi开发者_如何转开发c static T[] BubbleSort<T>(this T[] arr) where T : class
    {
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = 0; j < arr.Length-1; j++)
            {
                if (arr[j - 1] > arr[j])
                    swap(arr[j - 1], arr[j]);
            }
        }
    }

How can I create a generic bubble sort extension method? Is there any way to handle the comparing here ? Error 1 Operator '>' cannot be applied to operands of type 'T' and 'T'


You can restrict T to IComparable<T> like this:

public static void BubbleSort<T>(this T[] arr) where T : IComparable<T>
{
    for (int i = 0; i < arr.Length; i++)
    {
        for (int j = 0; j < arr.Length-1; j++)
        {
            if (arr[j].CompareTo(arr[j + 1]) > 0)
                swap(arr[j], arr[j + 1]);
        }
    }
}

which has the advantage that T can also be a value type like int. Also your function does not need to return the array as it changes the this array.


You can't use < on type parameters. So you could use Comparer<T>.Default.

Or you could just add a generic contraint that requires T to implement IComparable<T>. Then you can call the Compare method.

In addition your j loop is off by one. You either need to compare&swap arr[j] and arr[j+1] or change the lower bound to 1 and the upper to arr.Length


A couple of ways you could go about doing this:

  1. Require T to implement IComparable<T> and use the CompareTo method to do comparisons.
  2. Add a second parameter of type IComparer<T> that implements a custom comparison. You would then use this comparer object to do key comparisons.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜