冒泡排序(二:通過使用泛型和委託,實現通用排序方法)

首先是冒泡排序方法:

因爲方法是通用的,並不知道需要進行排序的類型是什麼,所以需要使用泛型,傳入的數組也是該泛型數組。

比較過程中,需要用到的方法通過委託作爲參數傳遞到冒泡排序方法內。

代碼如下:

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

輸出結果:

如需對其他類型進行排序,只需要修改自定義類中的對比方法即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章