标签:
归并排序利用分治的思想实现,其操作方式为:
(1)分解待排序的n个元素的序列成各具n/2个元素的两个子序列.
(2)使用归并排序递归地排序两个子序列.
(3)合并两个已排序的子序列以产生已排序的序列.
归并排序的时间复杂度是O(n*log2n)。算法处理过程中,需要一个大小为n的临时存储空间用以保存合并序列。在归并排序中,相等的元素的顺序不会改变,所以它是稳定的算法。
归并排序的关键操作是合并两个已排序的子序列.其算法如下:
merge(a, start, mid, end) temp[end - start + 1] be new array i = start, j = mid + 1, k = 0 while i <= mid and j <= end if a[i] <= a[j] temp[k++] = a[i++] else temp[k++] = a[j++] while i <= mid temp[k++] = a[i++] while j <= end temp[k++] = a[j++] j = 0 for i = start to end a[i] = temp[j++]
merge方法可以作为归并排序算法中的一个子程序来用.下面是merge-sort的算法:
sort(a) sort(a, 0, a.length - 1) sort(a, start, end) if start < end mid = (start + end) >> 1; sort(a, start, mid) sort(a, mid + 1, end) merge(a, start, mid, end)
java实现
package com.diysoul.algorithm.sort; import java.util.Random; public class MergeSort { public static void sort(int[] array) { sort(array, 0, array.length - 1); } public static void sort(int[] array, int start, int end) { if (start < end) { int mid = (start + end) / 2; sort(array, start, mid); sort(array, mid + 1, end); merge(array, start, mid, end); } } public static void merge(int[] array, final int start, final int mid, final int end) { int i = start, j = mid + 1, k = 0; int[] tempArray = new int[end - start + 1]; while (i <= mid && j <= end) { if (array[i] <= array[j]) { tempArray[k++] = array[i++]; } else { tempArray[k++] = array[j++]; } } while (i <= mid) { tempArray[k++] = array[i++]; } while (j <= end) { tempArray[k++] = array[j++]; } for (i = 0, k = start; k <= end; k++, i++) { array[k] = tempArray[i]; } } public static void main(String[] args) { int maxSize = 4; int min = -200; int max = 200; Random random = new Random(); int[] a = new int[maxSize]; for (int i = 0; i < a.length; i++) { a[i] = random.nextInt(max - min) + min; } print(a); MergeSort.sort(a); print(a); } private static void print(int[] array) { if (array == null || array.length == 0) return; System.out.print("array(" + array.length + "): "); int i = 0; for (; i < array.length - 1; i++) { System.out.print(array[i] + ", "); } System.out.println(array[i]); } }
标签:
原文地址:http://www.cnblogs.com/diysoul/p/5672048.html