通用冒泡扩展 [英] Generic BubbleSort Extension
本文介绍了通用冒泡扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public static T[] BubbleSort<T>(this T[] arr) where T : class
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length-1; j++)
{
if (arr[j - 1] > arr[j])
swap(arr[j - 1], arr[j]);
}
}
}
我如何创建一个通用冒泡排序扩展方法?有什么办法来处理这里比较?
错误1操作'>'不能应用于类型为'T'和'T'的操作数
How can I create a generic bubble sort extension method? Is there any way to handle the comparing here ? Error 1 Operator '>' cannot be applied to operands of type 'T' and 'T'
推荐答案
您可以限制 T
到 IComparable的< T>
是这样的:
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]);
}
}
}
其具有的优点是,Ť也可以是值类型,比如 INT
。此外,您的功能并不需要返回数组,因为它改变了这个
阵列。
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.
这篇关于通用冒泡扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文