Unity学习(C#)——冒泡排序改进

    技术2023-07-23  91

    class Program { static void Sort(int[] array) { bool swapped = true; do { swapped = false; for (int i = 0; i < array.Length - 1; i++) { if (array[i] > array[i + 1]) { int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true;//如果发生了交换,那么循环将继续,如果没有发生,swapped仍然为false,则说明顺序已经正确,循环结束。 } } } while (swapped); } static void Main(string[] args) { int[] Array = { 34, 5, 6, 764, 67 }; Sort(Array); foreach (var temp in Array) { Console.WriteLine(temp); } Console.ReadKey(); } }

    冒泡排序拓展 其他数据类型的排序

    class Employee//定义employee类 { public string Name { get; private set; } public int Salary { get; private set; } public Employee(string name, int salary) { this.Name = name; this.Salary = salary; } public static bool Compare(Employee e1,Employee e2) { if (e1.Salary > e2.Salary) return true; return false; } } static void CommonSort<T>(T[] array,Func<T,T,bool> compareMethod)//T表示数据类型不确定,使用委托。 { bool swapped = true; do { swapped = false; for (int i = 0; i < array.Length - 1; i++) { if (compareMethod(array[i],array[i + 1])) { T temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true; } } } while (swapped); } static void Main(string[] args) { Employee[] employees = new Employee[] { new Employee("a", 12), new Employee("b", 34), new Employee("c", 5) }; CommonSort<Employee>(employees,Employee.Compare); foreach (Employee em in employees) { Console.WriteLine(em.Salary); } Console.ReadKey(); }
    Processed: 0.013, SQL: 9