明耀

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
import java.util.*;
public class Main {
	public static void main(String[] args)
	{
		int[] num={2,1,45,13,34,43,25,9,6,11};
		MergeSort(num,0,num.length-1);
		for(int i=0;i<num.length;i++)
			System.out.println(num[i]);
	}
	public static void MergeSort(int[] num,int left,int right)
	{
		if(left<right)
		{
			int middle=(left+right)/2;
			MergeSort(num,left,middle);
			MergeSort(num,middle+1,right);
			Merge(num,left,middle,right);
		}
	}
	public static void Merge(int[] num,int left,int middle,int right)
	{
		int[] tmp=new int[right-left+1];
		int i=left,j=middle+1,k=0;
		while(i<=middle&&j<=right)
		{
			if(num[i]<num[j])
				tmp[k++]=num[i++];
			else
				tmp[k++]=num[j++];
		}
		if(i<=middle)
		{
			while(i<=middle)
				tmp[k++]=num[i++];
		}
		if(j<=right)
		{
			while(j<=right)
				tmp[k++]=num[j++];
		}
		for(i=0;i<tmp.length;i++)
			num[i+left]=tmp[i];
	}

}

  

posted on 2017-08-12 10:04  明耀  阅读(145)  评论(0编辑  收藏  举报