Unity之C#——利用泛型與委託拓展氣泡排序
阿新 • • 發佈:2018-11-27
利用泛型與委託拓展氣泡排序
氣泡排序一般只適用於一些可直接比較大小的單個值,如果遇到比較物件陣列中某一個屬性,對物件陣列中的元素進行排序,就顯得不適用了,例如有一組學生物件,將他們存入陣列中,比較他們中的分數來將該物件陣列進行氣泡排序,這時就需要利用泛型與委託來實現。
以下是程式碼部分:
執行效果如下: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(); } } }
歡迎大家提出你的想法,互相學習,進步!繼續成長之路!