Generic BubbleSort Extension

后端 未结 3 1477
长发绾君心
长发绾君心 2021-01-23 12:49
    public static T[] BubbleSort(this T[] arr) where T : class
    {
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = 0; j <         


        
相关标签:
3条回答
  • 2021-01-23 13:24

    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 讨论(0)
  • 2021-01-23 13:31

    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

    0 讨论(0)
  • 2021-01-23 13:38

    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.

    0 讨论(0)
提交回复
热议问题