Java排序五:归并排序

public class TestDemo {
	public static void main(String[] args) {
		int[] arr = new int[10];
		Random random = new Random();
		for (int i = 0; i < arr.length; i++) {
			arr[i] = random.nextInt(100);
		}
		display(arr);
		sort(arr, 0, arr.length - 1);
		display(arr);
	}

	public static void sort(int[] arr, int left, int right) {
		if (left >= right)
			return;
		int middle = (left + right) >> 0x1;
		sort(arr, left, middle);
		sort(arr, middle + 1, right);
		merge(arr, left, middle, right);
	}

	private static void merge(int[] arr, int left, int middle, int right) {
		int[] tmpArr = new int[arr.length];
		int tmpIndex, startIndex;
		tmpIndex = startIndex = left;
		int secLeft = middle + 1;
		while (left <= middle && secLeft <= right) {
			if (arr[left] <= arr[secLeft]) {
				tmpArr[tmpIndex++] = arr[left++];
			} else {
				tmpArr[tmpIndex++] = arr[secLeft++];
			}
		}
		while (left <= middle) {
			tmpArr[tmpIndex++] = arr[left++];
		}
		while (secLeft <= right) {
			tmpArr[tmpIndex++] = arr[secLeft++];
		}

		System.arraycopy(tmpArr, startIndex, arr, startIndex, right - startIndex + 1);
	}

	private static void swap(int[] arr, int i, int j) {
		if (i == j) {
			return;
		}
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}

	private static void display(int[] arr) {
		for (int i = 0, len = arr.length; i < len; i++) {
			System.out.print(arr[i] + "  ");
		}
		System.out.println();
	}
}

你可能感兴趣的:(Java排序五:归并排序)