static void Main (string[] args)
{
//傳入一個學生集合
Stu[] s = new Stu[]
{
new Stu{ ID = 1,Name = "張三",Age = 19 },
new Stu{ ID = 2,Name = "李四",Age = 20 },
new Stu{ ID = 3,Name = "王五",Age = 18 }
};
//調用泛型冒泡排序
var n = sort<Stu>(s);
//遍歷輸出排序後的學生姓名
foreach (var item in n)
{
Console.WriteLine(item.Name);
}
Console.ReadKey();
}
//泛型數組 冒泡排序
static T[] sort<T>(T[] x) where T:IComparable<T>
{
T b = default(T);
for (int i = 0; i < x.Length-1; i++)
{
for (int j = 0; j < x.Length-i-1; j++)
{
if (x[j].CompareTo(x[j+1])<0)
{
b = x[j];
x[j] = x[j + 1];
x[j + 1] = b;
}
}
}
return x;
}
//繼承接口
public class Stu:IComparable<Stu>
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Stu other)
{
//根據年齡來排序
return this.Age.CompareTo(other.Age);
}
}
C#調用泛型冒泡實現學生類排序IComparable
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.