經典排序演算法,排序演算法

來源:互聯網
上載者:User

經典排序演算法,排序演算法

經典排序演算法 - 歸併排序Merge sort

原理,把原始數組分成若干子數組,對每一個子數組進行排序,

繼續把子數組與子數組合并,合并後仍然有序,直到全部合并完,形成有序的數組

舉例

無序數組[6 2 4 1 5 9]

先看一下每個步驟下的狀態,完了再看合并細節

第一步 [6 2 4 1 5 9]原始狀態

第二步 [2 6] [1 4] [5 9]兩兩合并排序,排序細節後邊介紹

第三步 [1 2 4 6] [5 9]繼續兩組兩組合并

第四步 [1 2 4 5 6 9]合并完畢,排序完畢

輸出結果[1 2 4 5 6 9]

合并細節

詳細介紹第二步到第三步的過程,其餘類似

第二步:[2 6] [1 4] [5 9]

兩兩合并,其實僅合并[2 6] [1 4],所以[5 9]不管它,

原始狀態

第一個數組[2 6]

第二個數組[1 4]

--------------------

第三個數組[...]

 

第1步,順序從第一,第二個數組裡取出一個數字:2和1

比較大小後將小的放入第三個數組,此時變成下邊這樣

第一個數組[2 6]

第二個數組[4]

--------------------

第三個數組[1]

 

第2步,繼續剛才的步驟,順序從第一,第二個數組裡取資料,2和4,

同樣的比較大小後將小的放入第三個數組,此時狀態如下

第一個數組[6]

第二個數組[4]

--------------------

第三個數組[1 2]

 

第3步,再重複前邊的步驟變成,將較小的4放入第三個數組後變成如下狀態

第一個數組[6]

第二個數組[...]

--------------------

第三個數組[1 2 4]

 

第4步,最後將6放入,排序完畢

第一個數組[...]

第二個數組[...]

--------------------

第三個數組[1 2 4 6]

 

[ 1 2 4 6 ]與[ 5 9 ]的合并過程與上邊一樣,不再分解

代碼僅供參考

        static void merge(int[] unsorted, int first, int mid, int last, int[] sorted)        {            int i = first, j = mid;            int k = 0;            while (i < mid && j < last)                if (unsorted[i] < unsorted[j])                    sorted[k++] = unsorted[i++];                else                    sorted[k++] = unsorted[j++];            while (i < mid)                sorted[k++] = unsorted[i++];            while (j < last)                sorted[k++] = unsorted[j++];            for (int v = 0; v < k; v++)                unsorted[first + v] = sorted[v];        }        static void merge_sort(int[] unsorted, int first, int last, int[] sorted)        {            if (first + 1 < last)            {                int mid = (first + last) / 2;                Console.WriteLine("{0}-{1}-{2}", first, mid, last);                merge_sort(unsorted, first, mid, sorted);                merge_sort(unsorted, mid, last, sorted);                merge(unsorted, first, mid, last, sorted);            }        }        static void Main(string[] args)        {            int[] x = { 6, 2, 4, 1, 5, 9 };            int[] sorted = new int[x.Length];            merge_sort(x, 0, x.Length, sorted);            for (int i = 0; i < sorted.Length; i++)            {                if (x[i] > 0)                    Console.WriteLine(x[i]);            }            Console.ReadLine();        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.