1

I want to sort an array of either integers or doubles. For this i want to use one method. My problem is that I don't know how to pass an array with an unknown type as a parameter. I tried this

public static void BubbleSort<T>(T[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = 0; j < arr.Length - 1; j++)
            {
                //Can't use greater than because of T
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

But now I can't use the greater than operator because the array could also be an array of strings.

N.Kewitsch
  • 59
  • 10

3 Answers3

7

You could add a constraint:

public static void BubbleSort<T>(T[] arr)
    where T : IComparable<T>
{
   ...
}

Then the CompareTo method will become available:

if (arr[j].CompareTo(arr[j + 1]) > 0)
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
0

Simply put, I wouldn't try to do the sort myself for this. There is build in support for this inside the framework.

https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.7.2

Unless this is a homework assignment or a technical interview, there is very little reason to implement this your self.

KingCronus
  • 4,509
  • 1
  • 24
  • 49
0

When you want to compare, IComparer<T> is a choice:

public static void BubbleSort<T>(T[] arr, IComparer<T> comparer = null) {
  if (null == arr)
    throw new ArgumentNullException(nameof(arr));

  // If comparer is not provided, let's (try to) use default one   
  if (null == comparer && typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
    comparer = Comparer<T>.Default;
  else
    throw new ArgumentNullException(
       nameof(comparer), 
     $"Type {typeof(T)} doesn't have reasonable default comparer.");

  for (int i = 0; i < arr.Length; i++) {
    for (int j = 0; j < arr.Length - 1; j++) {
      // Can't use greater than because of T: but can comparer.Compare
      if (comparer.Compare(arr[j], arr[j + 1]) > 0) {
        T temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
}

Now we can sort

  int[] ints = ...

  // integer array (default comparer)
  BubbleSort(ints); 

  int[] doubles = ...

  // double array (default comparer)
  BubbleSort(doubles); 

  // button array with custom comparer (sort by buttons' names)
  Button[] buttons = ...;

  BubbleSort(data, 
    Comparer<Button>.Create((left, right) => string.Compare(left?.Text, right?.Text)));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215