算法 - 选择排序(C#)

/*
 * 每一趟从待排序的数据元素中选出最小(或最大)的一个元素,
 * 顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完为止。
 * 选择排序是不稳定的排序算法。
 */
 
namespace SelectionSort
{
    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 + " ");
            }
        }
 
        /// <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++)
            {
                // 存储最小元素的index。
                int min = i;
 
                // 寻找最小元素的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;
 
                // 打印数组。
                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 5
In Selection Sort:
1 6 4 2 8 7 9 3 10 5
1 2 4 6 8 7 9 3 10 5
1 2 3 6 8 7 9 4 10 5
1 2 3 4 8 7 9 6 10 5
1 2 3 4 5 7 9 6 10 8
1 2 3 4 5 6 9 7 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 8 10 9
1 2 3 4 5 6 7 8 9 10
After Selection Sort:
1 2 3 4 5 6 7 8 9 10
*/

猜你喜欢

转载自blog.csdn.net/qq_24624539/article/details/91350495