[C#] 合併排序法(Merge Sort)

  • 9269
  • 0

[C#] 合併排序法(Merge Sort)

Introduction

將資料不停的等分兩堆(遞回),然後反向逐一合併。

 

Examples


    class Program {
        /// <summary>
        /// 組合排序。
        /// </summary>
        /// <param name="list">串列。</param>
        /// <param name="left">左邊極限。</param>
        /// <param name="right">右邊極限。</param>
        public static void mergeSort(int[] list, int left, int right) {
            int mid;
            if (left < right) {
                mid = (left + right) / 2;
                mergeSort(list, left, mid);//排序左半邊
                mergeSort(list, mid + 1, right);//排序右半邊
                merge(list, left, mid, right);//組合
            }
        }

        public static void merge(int[] list, int left, int mid, int right) {
            int[] temp = new int[right - left + 1];//設定暫存陣列長度
            int left1 = left, left2 = mid + 1, index = 0;//設定左邊極限
            while ((left1 <= mid) && (left2 <= right)) {
                if (list[left1] < list[left2]) {
                    temp[index] = list[left1];
                    left1++;
                    index++;
                } else {
                    temp[index] = list[left2];
                    left2++;
                    index++;
                }
            }
            while (left1 <= mid) {
                temp[index] = list[left1];
                left1++;
                index++;
            }
            while (left2 <= right) {
                temp[index] = list[left2];
                left2++;
                index++;
            }
            for (int i = 0; i < right - left + 1; i++)
                list[left + i] = temp[i];
        } 

        static void Main(string[] args) {
            int[] list = new int[10] {5,10,21,55,11,77,23,56,45,65 };
            Console.WriteLine("Before sort");
            for (int n = 0; n < list.Length; n++)
                Console.Write(list[n] + " ");
            mergeSort(list, 0, list.Length - 1);
            Console.WriteLine("\nAfter sort");
            for (int n = 0; n < list.Length; n++)
                Console.Write(list[n] + " ");

            Console.ReadKey();
        }
    }

 

輸出結果

2010-05-03_212344

三小俠  小弟獻醜,歡迎指教