冒泡排序, 一个良好的算法, 是既可以比较int ,float, string ,而非只是其中一种。
。那么该如何做? 一个方法是,重载函数, 写多份代码。
另外一个则是泛型!!!! 是泛型,而不是重载运算符, 重载运算符号指的是:必须明确具体的类型进行重载,不能空洞,不明确类型进行重载。
实现一个比较大小的接口IComparable即可。由于是基本的数据类型,所以没有必要重写IComparable接口中的CompareTo方法。
class Test<T> where T :IComparable
{
//冒泡排序
public void BubbleSort(T [] a, int n)
{
int i, j;
T temp;
bool flag=false;
for(i=n-1;i>=0;i--)
{
flag=false;
for(j=0;j<i;j++)
{
if (a[j + 1].CompareTo(a[j]) < 0) //注意这一行 ,如果小于,则返回小于0的数字,依次类推
{
temp=a[j+1]; a[j+1]=a[j]; a[j]=temp;
flag=true;
}
}
if(flag==false) break;
}
} //end BubbleSort
} //end Test
class MainClass
{
static void Main()
{
const int n = 5;
int[] a = new int[n] { 23, 4, 5, 9, 0 };
float[] b = new float[n] { 2.0f, 2.3f, 1f, 8.9f, 0.9f };
Test<int> test1 = new Test<int>();
Test<float> test2 = new Test<float>();
test1.BubbleSort(a, n);
test2.BubbleSort(b, n);
foreach(int i in a)
Console.WriteLine(i);
foreach(int j in b)
Console.WriteLine(j);
}
}
我的意思是,你应该回头看看你自己的最初的想法,你写的“于是我就在类中重载了”。可是这个时候你根本不可能重载,因为你不知道T具体是什么,在Test<T>中是不能为空洞的T对象的运算进行重载的。只有在具体类型的源代码的class中,你才可以重载。
对于静态函数,能否实现泛型?
是可以的,
class Test<T> where T :IComparable private static int size = 90; //冒泡排序 bool flag=false; for(i=n-1;i>=0;i--) for(j=0;j<i;j++) if (a[j + 1].CompareTo(a[j]) < 0)
} if(flag==false) break; }
} //end Test
class MainClass const int n = 5; int[] a = new int[n] { 23, 4, 5, 9, 0 }; float[] b = new float[n] { 2.0f, 2.3f, 1f, 8.9f, 0.9f };
Test<int>.BubbleSort(a, n); foreach (int i in a)
foreach (float j in b) } |