归并排序_java实现

public class MergeSort {
	private static int n=10;
	public static void main(String[] args) {
		int a[] = new int [n];//待排序数组
		int sort[] = new int [n];//所借助的另一个数组
		Scanner sc = new Scanner(System.in);
		for(int i = 0;i<a.length;i++){
			a[i] = sc.nextInt();
		}
		mergeSort(a,sort,0,a.length-1);
		for(Integer obj:a){
			System.out.println(obj);
		}
	}

	private static void mergeSort(int[] unsort, int[] sort, int left, int right) {
		if(left>=right){
			return;
		}
		int mid = (left+right)/2;
		mergeSort(unsort,sort,left,mid);//mid归后半段数组
		mergeSort(unsort, sort, mid+1, right);
		sort(unsort,sort,left,right,mid);
	}

	private static void sort(int[] unsort, int[] sort, int left, int right,
			int mid) {
		int i = left;
		int j = mid+1;
		int t = 0;//对数组中的一段进行排序,借助另一个数组为中转
		while(i<=mid&&j<=right){
			if(unsort[i]<unsort[j]){
				sort[t++] = unsort[i];
				i++;
			}else{
				sort[t++] = unsort[j];
				j++;
			}
		}
		while(i<=mid)
			sort[t++] = unsort[i++];
		while(j<=right)
			sort[t++] = unsort[j++];
		for(int x = 0;x<t;x++)
			unsort[left+x] = sort[x];
	}
}

点赞