插入排序-C#實現

來源:互聯網
上載者:User

標籤:pre   amp   sort   改進   元素   div   ++   希爾   情況   

插入排序包括:直接插入排序和希爾排序。

具體代碼如下:

直接插入排序:

        /// <summary>        /// 直接插入排序        /// 適用於少量元素的排序        /// 穩定性:穩定        /// 時間複雜度:O(n2)        /// </summary>        public static void SimpInsertSort(int[] array)        {            int temp = 0;            for (int i = 1; i < array.Length; i++)            {                if (array[i] < array[i - 1])                {                    temp = array[i];                    int j = 0;                    for (j = i - 1; j >= 0 && temp < array[j]; j--)                    {                        array[j + 1] = array[j];                    }                    array[j + 1] = temp;                }            }        }

 

希爾排序:

        /// <summary>        /// 希爾排序  縮小增量排序        /// 是直接插入排序的改進版        /// 穩定性:不穩定        /// 平均時間複雜度:O(Nlog2N),最壞情況下為O(N1.5)        /// </summary>        public static void ShellSort(int[] array)        {            int gap = array.Length / 2;            while (gap > 0)            {                //直接插入排序                for (int i = 0; i < gap; i++)                        {                    for (int j = i + gap; j < array.Length; j += gap)                    {                        if (array[j] < array[j - gap])                        {                            int temp = array[j];                            int k = j - gap;                            while (k >= 0 && array[k] > temp)                            {                                array[k + gap] = array[k];                                k -= gap;                            }                            array[k + gap] = temp;                        }                    }                }                gap = gap / 2;            };        }

 

插入排序-C#實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.