1. 程式人生 > >插入排序(C#)

插入排序(C#)

               
// --------------------------------------------------------------------------------------------------------------------// <copyright file="Program.cs" company="Chimomo's Company">//// Respect the work.//// </copyright>// <summary>//// The insertion sort.//// 直接插入排序(straight insertion sort)的做法是:// 每次從無序表中取出第一個元素,把它插入到有序表的合適位置使有序表仍然有序,直至無序表中所有元素插入完為止。
// 第一趟掃描前兩個數,然後把第二個數按大小插入到有序表中;第二趟把第三個數與前兩個數從前向後掃描,把第三個數按大小插入到有序表中;依次進行下去,進行了(n-1)趟掃描以後就完成了整個排序過程。// 直接插入排序屬於穩定的排序,最壞時間複雜度為O(n^2),空間複雜度為O(1)。// 直接插入排序是由兩層巢狀迴圈組成的。外層迴圈標識並決定待比較的數值,內層迴圈為待比較數值確定其最終位置。直接插入排序是將待比較的數值與它的前一數值進行比較,所以外層迴圈是從第二個數值開始的。當前一數值比待比較數值大的情況下後移該數值並繼續迴圈比較,直到找到比待比較數值小的並將待比較數值插入其後一位置,結束該次迴圈。// 值得注意的是,我們必需用一個儲存空間來儲存當前待比較的數值,因為當一趟比較完成時,我們要將待比較數值插入比它小的數值的後一位置。插入排序類似於玩紙牌時整理手中紙牌的過程。
//// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{    using System;    /// <summary>    /// The program.    /// </summary>    public static class Program    {        /// <summary>        ///
The main.
        /// </summary>        public static void Main()        {            int[] a = { 1, 4, 6, 2, 8, 7, 9, 3, 5, 10 };            Console.WriteLine("Before Insertion Sort:");            foreach (int i in a)            {                Console.Write(i + " ");            }            Console.WriteLine("\r\n\r\nIn Insertion Sort:");            InsertionSort(a);            Console.WriteLine("\r\nAfter Insertion Sort:");            foreach (int i in a)            {                Console.Write(i + " ");            }            Console.WriteLine(string.Empty);        }        /// <summary>        /// The insertion sort.        /// </summary>        /// <param name="a">        /// The a.        /// </param>        public static void InsertionSort(int[] a)        {            // 從第二個元素開始迭代。            for (int i = 1; i < a.Length; i++)            {                int tmp = a[i]; // 儲存待插入的元素。                int j = i - 1;                // 從當前元素右邊尋找插入點。                while (a[j] > tmp)                {                    a[j + 1] = a[j]; // 後移。                    j--;                    if (j == -1)                    {                        break;                    }                }                a[j + 1] = tmp; // 該後移的元素已經後移了,會留下一個空位置,這個位置就是待插入元素的插入點。                // 列印陣列。                foreach (int k in a)                {                    Console.Write(k + " ");                }                Console.WriteLine(string.Empty);            }        }    }}// Output:/*Before Insertion Sort:1 4 6 2 8 7 9 3 5 10In Insertion Sort:1 4 6 2 8 7 9 3 5 101 4 6 2 8 7 9 3 5 101 2 4 6 8 7 9 3 5 101 2 4 6 8 7 9 3 5 101 2 4 6 7 8 9 3 5 101 2 4 6 7 8 9 3 5 101 2 3 4 6 7 8 9 5 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10After Insertion Sort:1 2 3 4 5 6 7 8 9 10*/