Generic BubbleSort Extension

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

    You can restrict T to IComparable like this:

    public static void BubbleSort(this T[] arr) where T : IComparable
    {
        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.

提交回复
热议问题