選擇排序(C#)
阿新 • • 發佈:2019-01-11
// --------------------------------------------------------------------------------------------------------------------// <copyright file="Program.cs" company="Chimomo's Company">//// Respect the work.//// </copyright>// <summary>//// The selection sort.//// 每一趟從待排序的資料元素中選出最小(或最大)的一個元素,順序放在已排好序的數列的最後,直到全部待排序的資料元素排完為止。選擇排序是不穩定的排序演算法。 //// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{ using System; /// <summary> /// The program. /// </summary> public static class Program { /// <summary> /// The main. /// </summary> public static void Main() { int[] a = { 1, 6, 4, 2, 8, 7, 9, 3, 10, 5 }; Console.WriteLine("Before Selection Sort:"); foreach (int i in a) { Console.Write(i + " "); } Console.WriteLine("\r\n\r\nIn Selection Sort:" ); SelectionSort(a); Console.WriteLine("\r\nAfter Selection Sort:"); foreach (int i in a) { Console.Write(i + " "); } Console.WriteLine(string.Empty); } /// <summary> /// The selection sort. /// </summary> /// <param name="a"> /// The a. /// </param> private static void SelectionSort(int[] a) { for (int i = 0; i < a.Length - 1; i++) { int min = i; // 儲存最小元素的index。 // 尋找最小元素的index。 for (int j = i + 1; j < a.Length; j++) { if (a[j] < a[min]) { min = j; } } int tmp = a[min]; a[min] = a[i]; a[i] = tmp; Console.Write("Round {0}: ", i + 1); // 列印陣列。 foreach (int k in a) { Console.Write(k + " "); } Console.WriteLine(string.Empty); } } }}// Output:/*Before Selection Sort:1 6 4 2 8 7 9 3 10 5In Selection Sort:Round 1: 1 6 4 2 8 7 9 3 10 5Round 2: 1 2 4 6 8 7 9 3 10 5Round 3: 1 2 3 6 8 7 9 4 10 5Round 4: 1 2 3 4 8 7 9 6 10 5Round 5: 1 2 3 4 5 7 9 6 10 8Round 6: 1 2 3 4 5 6 9 7 10 8Round 7: 1 2 3 4 5 6 7 9 10 8Round 8: 1 2 3 4 5 6 7 8 10 9Round 9: 1 2 3 4 5 6 7 8 9 10After Selection Sort:1 2 3 4 5 6 7 8 9 10*/