您的位置:首页 > 其它

归并排序

2015-09-03 10:31 232 查看
看了下思路,实现了下。发现在将数组的两段合并的时候出了点问题,改了有十来分钟。

之前在leetcode上做过一道题,将两个已经排序好的数组进行合并。归并排序的思路也是如此。归并排序采用的是递归的方法,在递归的最底层是一个个的单独的数字,两个数字按照顺序先合并,然后在进行过一次合并的这一层,再两两合并(此时要合并的两段已经是排序的了,因此用leetcode上的那道题的解题思路去实现就行)。由于合并过程都是在一个数组上进行的,因此对于下标要搞清楚。

代码:

package codes;

public class MergeSort {

	public static void main(String[] args) {
        int [] arr = {3,4,6,10,1,2,9,7};
        new MergeSort().mergeSort(arr);
        for(int i=0;i< arr.length;i++){
        	System.out.print(" "+arr[i]);
        }
	}
	
	public void mergeSort(int []nums){
		merge(nums,0,nums.length-1);
	}
	
	public void merge(int [] nums,int low, int high){
		if(low<high){
			int mid = (low + high)/2;
			merge(nums,low,mid);
			merge(nums,mid+1,high);
			mergeArray(nums,low,mid,high);
		}
		
	}
	public void mergeArray(int[] nums, int low, int mid, int high ){
		int [] tmp = new int[nums.length];
		int p1=low,p2 = mid+1;
		int count =0;
		while(p1 <= mid && p2 <= high){
			if(nums[p1]<=nums[p2]){
				tmp[count++] = nums[p1++];
			}else{
				tmp[count++] = nums[p2++];
			}
		}
		
		while(p1<=mid){
			tmp[count++] = nums[p1++];
		}
		while(p2<=high){
			tmp[count++] = nums[p2++];
		}
		for( int i=0;i<count;i++){
			nums[low+i] = tmp[i];//copy 这里会写错。。
		}
	}
	

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: