Unity之C#——利用泛型与委托拓展冒泡排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lijianfex/article/details/78261452

       利用泛型与委托拓展冒泡排序

       冒泡排序一般只适用于一些可直接比较大小的单个值,如果遇到比较对象数组中某一个属性,对对象数组中的元素进行排序,就显得不适用了,例如有一组学生对象,将他们存入数组中,比较他们中的分数来将该对象数组进行冒泡排序,这时就需要利用泛型与委托来实现。

以下是代码部分:

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

namespace _001_泛型与委托_冒泡排序拓展
{
    /// <summary>
    /// 学生类
    /// </summary>
    class Student
    {
        //属性姓名
        public string Name { get; private set; }
        //属性分数
        public int Record { get; private set; }
        //构造函数
        public Student(string name, int record)
        {
            this.Name = name;
            this.Record = record;
        }

        //比较方法
        public static bool Compare(Student s1, Student s2)
        {
            if (s1.Record > s2.Record)
            {
                return true;
            }
            return false;
        }

        //重写ToString方法
        public override string ToString()
        {
            return Name + ":" + Record;
        }
    }

    /// <summary>
    /// Program类
    /// </summary>
    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++)
                {
                    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[] students = new Student[]
               {
                    new Student("李四",100),
                    new Student("张三",80),
                    new Student("王五",90),
                    new Student("刘二",30),
                    new Student("万一",60),
                    new Student("周六",70)
                };

            CommonSort<Student>(students, Student.Compare);
            //遍历输出对象数组
            foreach (Student em in students)
            {
                Console.WriteLine(em.ToString());
            }
            Console.ReadKey();

        }
    }
}
运行效果如下:


欢迎大家提出你的想法,互相学习,进步!继续成长之路!

猜你喜欢

转载自blog.csdn.net/lijianfex/article/details/78261452