浅尝通用排序(C# 课堂示例)
1、排序算法(例程)
public void Sort(Object[] objs)
{
for (int i = 0; i < objs.Length; i++)
{
for (int j = 0; j < objs.Length - i - 1; j++)
{
if (objs[j] > objs[j + 1])
{
Object tmp = objs[j];
objs[j] = objs[j + 1];
objs[j + 1] = tmp;
}
}
}
}
2、现有一些类型的数据需要完成排序,IntData,DoubleData,StringData,StudentData等;想创建一个排序方法,能够对这些类型的数据数组进行排序
public abstract class Data
{
public abstract bool Comparer(Data obj);
}
class StudentData : Data
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
double _score;
public double Score
{
get { return _score; }
set { _score = value; }
}
public override bool Comparer(Data obj)
{
return this._age > ((StudentData)obj)._age;
}
}
class IntData : Data
{
int _num;
public int Num
{
get { return _num; }
set { _num = value; }
}
public override bool Comparer(Data obj)
{
return this._num > ((IntData)obj)._num;
}
}
class Sorter
{
public static void Sort(Data[] objs)
{
for (int i = 0; i < objs.Length; i++)
{
for (int j = 0; j < objs.Length - i - 1; j++)
{
if (objs[j].Comparer(objs[j + 1]))
{
Data tmp = objs[j];
objs[j] = objs[j + 1];
objs[j + 1] = tmp;
}
}
}
}
}
(此处抽象类可更换为接口)
3、现又要求能够对学生数据按照不同的要求进行排序,如按Age,按Score排序,采用委托实现
class StudentData
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
double _score;
public double Score
{
get { return _score; }
set { _score = value; }
}
public static bool ComparerAge(Object stu1, Object stu2)
{
return ((StudentData)stu1)._age > ((StudentData)stu2)._age;
}
public static bool ComparerScore(Object stu1, Object stu2)
{
return ((StudentData)stu1)._score > ((StudentData)stu2)._score;
}
}
public delegate bool CallCompare(Object num1, Object num2);
class Sorter
{
public static void Sort(Object[] objs, CallCompare cmp)
{
for (int i = 0; i < objs.Length; i++)
{
for (int j = 0; j < objs.Length - i - 1; j++)
{
if (cmp(objs[j], objs[j + 1]))
{
Object tmp = objs[j];
objs[j] = objs[j + 1];
objs[j + 1] = tmp;
}
}
}
}
}
(Sort方法的Object也可用泛型来实现类型参数化代替)