歸併排序——「遞歸+合併」(Java版)

歸併排序是創建在歸併操做上的一種有效的排序算法。該算法是採用分治法(Divide and Conquer)的一個很是典型的應用。java

首先考慮下如何將將二個有序數列合併。這個很是簡單,只要從比較二個數列的第一個數,誰小就先取誰,取了後就在對應數列中刪除這個數。而後再進行比較,若是有數列爲空,那直接將另外一個數列的數據依次取出便可。算法

// 將有序數組a[]和b[]合併到c[]中  三個while循環
	public static void megerArray(int[] a, int n, int[] b, int m, int[] c) {
		int i = 0, j = 0, k = 0;
		while (i < n && j < m) {

			if (a[i] < b[j]) {
				c[k++] = a[i++];
			} else {
				c[k++] = b[j++];
			}
		}

		while (i < n) {
			c[k++] = a[i++];
		}
		while (j < m) {
			c[k++] = b[j++];
		}
	}

能夠看出合併有序數列的效率是比較高的,能夠達到O(n)。數組

解決了上面的合併有序數列問題,再來看歸併排序,其的基本思路就是將數組分紅二組A,B,若是這二組組內的數據都是有序的,那麼就能夠很方便的將這二組數據進行排序。如何讓這二組組內數據有序了?ide

能夠將A,B組各自再分紅二組。依次類推,當分出來的小組只有一個數據時,能夠認爲這個小組組內已經達到了有序,而後再合併相鄰的二個小組就能夠了。這樣經過先遞的分解數列,再合數列就完成了歸併排序。spa

package sort;

import java.util.Arrays;

public class MegerSort {
	// 將有序數組a[]和b[]合併到c[]中
	public static void megerArray(int[] a, int n, int[] b, int m, int[] c) {
		int i = 0, j = 0, k = 0;
		while (i < n && j < m) {

			if (a[i] < b[j]) {
				c[k++] = a[i++];
			} else {
				c[k++] = b[j++];
			}
		}

		while (i < n) {
			c[k++] = a[i++];
		}
		while (j < m) {
			c[k++] = b[j++];
		}
	}

	// 將有二個有序數列a[first...mid]和a[mid+1...last]合併。
	private static void mergeArray(int[] a, int frist, int mid, int last, int[] temp) {
		int i = frist;
		int j = mid + 1;
		int m = mid;
		int n = last;
		int k = 0;

		while (i <= m && j <= n) {
			if (a[i] <= a[j]) {
				temp[k++] = a[i++];
			} else {
				temp[k++] = a[j++];
			}
		}
		while (i <= m) {
			temp[k++] = a[i++];
		}
		while (j <= n) {
			temp[k++] = a[j++];
		}
		for (i = 0; i < k; i++){ //這步不能忘
			a[frist + i] = temp[i];
		}
	}

	public static void testMergeArray() {
		int[] a = { 1, 4, 6, 9, 2, 3, 8, 9 };

		int[] c = new int[a.length];
		mergeArray(a, 0, 3, 7, c);
		System.out.println(Arrays.toString(c));
	}

	public static void mergeSort(int[] a, int frist, int last, int[] temp) {
		if (frist < last) {
			int mid = (frist + last) / 2;
			mergeSort(a, frist, mid, temp);
			mergeSort(a, mid + 1, last, temp);
			mergeArray(a, frist, mid, last, temp);
		}
	}

	public static void main(String[] args) {
		int[] a = { 1, 4, 6, 9, 2, 3, 8, 9 };

		int[] c = new int[a.length];
		mergeSort(a, 0, 7, c);
		System.out.println(Arrays.toString(c));
	}
}

歸併排序的效率是比較高的,設數列長爲N,將數列分開成小數列一共要logN步,每步都是一個合併有序數列的過程,時間複雜度能夠記爲O(N),故一共爲O(N*logN)。由於歸併排序每次都是在相鄰的數據中進行操做,因此歸併排序在O(N*logN)的幾種排序方法(快速排序,歸併排序,希爾排序,堆排序)也是效率比較高的。code

相關文章
相關標籤/搜索