首先是冒泡排序方法:
因为方法是通用的,并不知道需要进行排序的类型是什么,所以需要使用泛型,传入的数组也是该泛型数组。
比较过程中,需要用到的方法通过委托作为参数传递到冒泡排序方法内。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 冒泡排序拓展
{
class Program
{
/// <summary>
/// 冒泡排序方法二
/// 通过泛型和委托,使得该方法变的随处可用,通用方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sortArray"></param>
/// <param name="compareMethod"></param>
static void CommonSort<T>(T[] sortArray,Func<T,T,bool> compareMethod)
{
bool swapped = true;
do
{
swapped = false;
for (int i = 0; i < sortArray.Length-1; i++)
{
// 使用传入的方法进行比较,该方法的返回值为bool类型
if (compareMethod(sortArray[i],sortArray[i+1]))
{
T temp = sortArray[i];
sortArray[i] = sortArray[i + 1];
sortArray[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
static void Main(string[] args)
{
}
}
}
定义一个类,使用冒泡排序对该类实例化出的对象的某一属性进行排序。在这里以自定义的Student类为例
定义一个Student类,其中包含Name以及Age两个属性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 冒泡排序拓展
{
class Student
{
public string Name { get; private set; }
public int Age { get; private set; }
public Student(string name, int age)
{
this.Name = name;
this.Age = age;
}
/// <summary>
/// 自定义类内的自定义比较方法
/// 用于根据自己的需要进行某个变量数值的比较并返回一个bool类型通知比较结果
/// </summary>
/// <param name="stu1">传入一个“学生”类型的变量</param>
/// <param name="stu2">传入一个“学生”类型的变量</param>
/// <returns></returns>
public static bool AgeCompare(Student stu1,Student stu2)
{
if (stu1.Age > stu2.Age)
{
return true;
}else {
return false;
}
}
/// <summary>
/// 重写了ToString()方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name + ":" + Age;
}
}
}
实例化出多个Student类型的对象,对它们的Age进行排序输出
在Main方法中写如下代码:
Student[] students = new Student[]
{
new Student("大头",15),
new Student("二头",16),
new Student("三头",13),
new Student("四头",11),
new Student("五头",19),
new Student("六头",12),
};
// 调用冒泡排序方法,进行排序
CommonSort<Student>(students, Student.AgeCompare);
foreach (var item in students)
{
Console.WriteLine(item.ToString());
}
Console.ReadKey();
输出结果:
如需对其他类型进行排序,只需要修改自定义类中的对比方法即可