public static T[] BubbleSort(this T[] arr) where T : class
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j <
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.