冒泡排序(泛型+委托)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{

static void Main(string[] args)
{
//声明一个类
People[] arrays = new People[5];
arrays[0] = new People("p1", 3);
arrays[1] = new People("p1",321);
arrays[2] = new People("p1", 12);
arrays[3] = new People("p1", 3231);
arrays[4] = new People("p1", 21);

//调用冒泡方法
SortMethod(arrays,People.ComPare);
//输出调用后
foreach (People P in arrays)
{
Console.WriteLine(P);
}
Console.ReadKey();
}
//定义冒泡方法
static bool isChange = false;
public static void SortMethod(People[] arrays,Func<int,int,bool> compare)
{
do
{
isChange = false;
for (int i = 0; i < arrays.Length - 1; i++)
{
if (compare(arrays[i].salary,arrays[i+1].salary))
{
People temp = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = temp;
isChange = true;
}
}
}
while (isChange);
}

}
}

下面是一个PeoPle类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class People
    {
        private string name;
        public int salary;
        public People(string name, int salary)
        {
            this.name = name;
            this.salary = salary;
        }
        public static bool ComPare(int salary1, int salary2)
        {
            if (salary1 > salary2) return true;
            return false;
        }
        //重写
        public override string ToString()
        {
            return name +","+salary.ToString();
        }
    }
}

 

posted @ 2017-07-14 22:43  BecaLove  阅读(493)  评论(0编辑  收藏  举报