码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2016-05-07 08:59:43      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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


package Sort;

public class MergeSort {
	private int num = 1; 
	public MergeSort(int[] data) {
		Sort(data, 0, data.length-1);
	}
	/**
	 * 将数组分割后归并
	 * @param data
	 * @param low
	 * @param high
	 */
	public void Sort(int[] data, int low, int high) {
		if(low>=high) return;
		int center = (low+high)/2;
		Sort(data, low, center);
		Sort(data, center+1, high);
		merge(data, low, center, high);
		print(data);
	}
	/**
	 * 将数组的两部分归并
	 * @param data
	 * @param low
	 * @param center
	 * @param high
	 */
	public void merge(int[] data, int low, int center, int high) {
		int[] temp = new int[data.length];
		int k = low, c = center+1, raw_low = low;
		while(low<=center && c<=high) {
			//将较小的数放入临时数组
			if(data[low]<data[c]) {
				temp[k++] = data[low++];
			}
			else
				temp[k++] = data[c++];
		}
		//将剩余的部分加入临时数组
		while(low<=center) {
			temp[k++] = data[low++];
		}
		while(c<=high) {
			temp[k++] = data[c++];
		}
		System.out.println("第" + num++ + "次归并:");
		//将临时数组复制到原数组中
		while(raw_low<=high) {
			System.out.print(data[raw_low] + " ");
			data[raw_low] = temp[raw_low++];
		}

		System.out.println();
	}
	
	public static void print(int[] data) {
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i] + " ");
		}
		System.out.println();
	}
	
	
	public static void main(String[] args) {
		int[] data = new int[]{5, 4, 1, 8, 6, 2};
		MergeSort ms = new MergeSort(data);
	}
	
}


归并排序

标签:

原文地址:http://blog.csdn.net/veson__/article/details/51333869

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!