java算法之归并排序

package com.hym.test.algorithms;

public class MergeSort {
	private int[] arrayTest = { 5, 26, 1, 783, 23, 2, 62, 9, 46 };

	public void mergeSort() {
		int[] workArray = new int[arrayTest.length];
		reMergeSort(workArray, 0, arrayTest.length - 1);
	}

	public void reMergeSort(int[] workArray, int begin, int end) {
		if (begin == end) {
			return;
		} else {
			int middle = (begin + end) / 2;

			reMergeSort(workArray, begin, middle);

			reMergeSort(workArray, middle + 1, end);

			merge(workArray, begin, middle + 1, end);
		}
	}

	public void merge(int[] workArray, int begin, int middle, int end) {
		int j = 0;
		int low = begin;
		int mid = middle - 1;
		int n = end - low + 1;

		while (begin <= mid && middle <= end) {
			if (arrayTest[begin] < arrayTest[middle]) {
				workArray[j++] = arrayTest[begin++];
			} else {
				workArray[j++] = arrayTest[middle++];
			}
		}

		while (begin <= mid) {
			workArray[j++] = arrayTest[begin++];
		}

		while (middle <= end) {
			workArray[j++] = arrayTest[middle++];
		}

		for (j = 0; j < n; j++) {
			arrayTest[low + j] = workArray[j];
		}
	}

	public static void main(String[] args) {
		MergeSort sort = new MergeSort();
		sort.mergeSort();
		for (int i = 0; i < sort.arrayTest.length; i++) {
			System.out.print(sort.arrayTest[i] + " ");
		}
	}
}


归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。

http://baike.baidu.com/view/90797.htm

你可能感兴趣的:(java算法)