java实现归并排序:

归并排序:显示不停的分割,一次分一半。。。直到分到全部为单个的时候,然后在慢慢合并回来。

代码:

package test2018926;

public class MergeSort {
	public static void main(String[] args) {
		Integer[] arr = { 1, 2, 3, 5, 4, 6 };
		mergeSort(arr);
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}

	public static void mergeSort(Integer[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		divide(arr, 0, arr.length - 1);
	}

	public static void divide(Integer[] arr, int start, int end) {
		if (start == end) {
			return;
		}
		// 取中间一个
		int mid = start + ((end - start) >> 1);
		divide(arr, start, mid);
		divide(arr, mid + 1, end);
		merge(arr, start, mid, end);
	}

	public static void merge(Integer[] arr, int start, int mid, int end) {
		// 定义两个指针,分别指向两边的开头,同时需要一个help临时辅助数组
		int i = 0;
		Integer[] help = new Integer[end - start + 1];
		int index1 = start;
		int index2 = mid + 1;
		// 然后取出小的放入到辅助数组中

		while (index1 <= mid && index2 <= end) {
			help[i++] = arr[index1] > arr[index2] ? arr[index2++] : arr[index1++];
		}
		// 退出上边的while循环说明至少有一边越界了,看那一边越界,然后继续添加
		while (index1 <= mid) {
			help[i++] = arr[index1++];
		}
		while (index2 <= end) {
			help[i++] = arr[index2++];
		}
		for (int j = 0; j < help.length; j++) {
			arr[start + j] = help[j];
		}
	}

}

控制台打印:

猜你喜欢

转载自blog.csdn.net/Handsome2013/article/details/82849728