views:

76

answers:

3

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();
        }

    }
+3  A: 
public static void BubbleSort<T>(T[] array, IComparer<T> comparer) {
  if (comparer == null) comparer = Comparer<T>.Default;
  T Swap;
  // etc..
}
Hans Passant
+1  A: 

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
{
   int Swap;
   for (int outer = Length; outer >= 1; outer--)
    {
        for (int inner = 0; inner < outer - 1; inner++)
        {
            if (array[inner].CompareTo(array[inner + 1]) > 0)
            {
                Swap = array[inner];
                array[inner] = array[inner + 1];
                array[inner + 1] = Swap;
            }

        }
    }
}
Itay
Will that handle nulls correctly? I see a NullReferenceException in that inner if-statement.
siride
no, it will not.
Itay
A: 
    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]);
                    }
                }                    
            }
        }
    }
Pro_Zeck
You should edit your question instead of posting your solution as an answer. :)
bzlm