Generic BubbleSort Extension

后端 未结 3 1473
长发绾君心
长发绾君心 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:31

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

    Or you could just add a generic contraint that requires T to implement IComparable. 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

提交回复
热议问题