开发者

How to create a Generic Bubble Sorting in c#

开发者 https://www.devze.com 2023-01-20 02:58 出处:网络
I am currently working on making my own Generic Bubble Sorting which can easily sort Strings, int. Below is my Code for Normal Bubble Sorting.Can you help me out how to create a generic Method Of this

I am currently working on making my own Generic Bubble Sorting which can easily sort Strings, int. Below is my Code for Normal Bubble Sorting.Can you help me out how to create a generic Method Of this?

public static void BubbleSorting()
{

       int Swap;
        for (int outer = Length; outer >= 1; outer--)
        {
            for (int inner = 0; inner < 开发者_运维知识库outer - 1; inner++)
            {
                if (array[inner] > array[inner + 1])
                {
                    Swap = array[inner];
                    array[inner] = array[inner + 1];
                    array[inner + 1] = Swap;
                }

            }
            Console.WriteLine();
            Display();
        }

    }


public static void BubbleSort<T>(T[] array, IComparer<T> comparer) {
  if (comparer == null) comparer = Comparer<T>.Default;
  T Swap;
  // etc..
}


Just use IComparable if the elements in the array implements IComparable you can replace

array[inner] > array[inner + 1]

with

array[inner].CompareTo(array[inner + 1]) > 0

so end up with

public static void BubbleSorting<T>(T[] array) where T : Icomparable
{
   for (int outer = Length; outer >= 1; outer--)
    {
        for (int inner = 0; inner < outer - 1; inner++)
        {
            if (array[inner].CompareTo(array[inner + 1]) > 0)
            {
                T Swap = array[inner];
                array[inner] = array[inner + 1];
                array[inner + 1] = Swap;
            }

        }
    }
}


    public static void BubbleSort<T>(T[] list) 
    { 
        BubbleSort<T>(list, Comparer<T>.Default); 
    }

    public static void BubbleSort<T>(T[] list, IComparer<T> comparer)
    {
        bool KeepIterating = true;
        while (KeepIterating)
        {
            KeepIterating = false;
            for (int i = 0; i < list.Length-1; i++)
            {
                T x = list[i];
                T y = list[i + 1];
                if (comparer.Compare(x,y)>0)
                {
                    list[i] = y;
                    list[i + 1] = x;
                    KeepIterating = true;

                    for (int j = 0; j < list.Length; j++)
                    {
                        Console.WriteLine("{0} {1}",j,list[j]);
                    }
                }                    
            }
        }
    }
0

精彩评论

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

关注公众号