归并排序之java实现

package com.cb.java.algorithms.sort;

/**
 * 归并排序
 * 
 * @author 36184
 *
 */
public class MergeSort{
	/**
	 * 将一个数组的两半(各自有序)合并到一个数组
	 * 
	 * @param a
	 * @param first
	 * @param mid
	 * @param last
	 * @param temp
	 */
	private static void mergeArray(int[] a, int first, int mid, int last, int[] temp) {
		int i = first;
		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[first + i] = temp[i];
		}
	}

	/**
	 * 递归调用上面的合并方法
	 * 
	 * @param arr
	 * @param first
	 * @param last
	 * @param temp
	 */
	public static void mergeSort(int[] arr, int first, int last, int[] temp) {
		if (first < last) {
			int mid = (first + last) / 2;
			mergeSort(arr, first, mid, temp);
			mergeSort(arr, mid + 1, last, temp);
			mergeArray(arr, first, mid, last, temp);
		}
	}

	public static void main(String[] args) {
		// int[] a = { 1, 2, 4, 9 };
		// int[] b = { 3, 5, 7, 8 };
		// int[] c = new int[a.length + b.length];
		// mergeArray(a, a.length - 1, b, b.length - 1, c);
		// for (int i : c) {
		// System.out.print(i + " ");
		// }

		int[] a = { 1, 2, 4, 9, 3, 5, 7, 8 };
		int[] c = new int[a.length];
		mergeSort(a, 0, a.length - 1, c);
		for (int i : c) {
			System.out.print(i + " ");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/81001295