码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序(泛型+委托)

时间:2017-07-14 23:54:53      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:arrays   委托   bsp   pac   threading   log   com   pre   eth   

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();
        }
    }
}

 

冒泡排序(泛型+委托)

标签:arrays   委托   bsp   pac   threading   log   com   pre   eth   

原文地址:http://www.cnblogs.com/trlq/p/7173017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!