归并排序 Merge sort

时间复杂度为 O(nlogn) 辅助储存空间O(n)
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);
            }
        }

你可能感兴趣的:(归并排序 Merge sort)