public static T[] BubbleSort(this T[] arr) where T : class
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j <
A couple of ways you could go about doing this:
IComparable<T> and use the CompareTo method to do comparisons.IComparer<T> that implements a custom comparison. You would then use this comparer object to do key comparisons.You can't use < on type parameters.
So you could use Comparer<T>.Default.
Or you could just add a generic contraint that requires T to implement IComparable<T>. 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
You can restrict T to IComparable<T> like this:
public static void BubbleSort<T>(this T[] arr) where T : IComparable<T>
{
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.