归并排序

public class Merge {

	public Merge(int a[]){
		int temp[] = new int[a.length];
		sortMerge(a,temp,0,a.length-1);
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
	}
	public void sortMerge(int a[], int temp[], int left, int right) {
		if (left < right) {
			int center = (left + right) / 2;
			sortMerge(a, temp, left, center);
			sortMerge(a, temp, center + 1, right);
			merge(a, temp,left,center,right);
		}
	}

	public void merge(int a[], int temp[],int leftPos,int leftEnd,int rightEnd) {
		int start = leftPos;
		int tempPos = leftPos;
		int rightPos = leftEnd + 1;
		while(leftPos <= leftEnd && rightPos <= rightEnd){
			if(a[leftPos] < a[rightPos])
				temp[tempPos++] = a[leftPos++];
			else
				temp[tempPos++] = a[rightPos++];
		}
		while(leftPos <= leftEnd)
			temp[tempPos++] = a[leftPos++];
		while(rightPos <= rightEnd)
			temp[tempPos++] = a[rightPos++];
		for(int i = start; i < tempPos; i++){
			a[i] = temp[i];
			System.out.print(a[i]+" ");			
		}
		System.out.println();
	}
	public static void main (String args[]){
		int a[] = {9,9,8,7,6,5,4,3};
		new Merge(a);
		System.out.println("");
		System.out.println("-------------");
		int b[] = {9,9,8,7,6,5,4,3,2,1};
		new Merge(b);
	}
}
运行结果:

 9 9 8 7 6 5 4 3
[9 9 8 7 ][6 5 4 3]
[9 9][8 7][6 5][4 3]
9 9
7 8
7 8 9 9
5 6
3 4
3 4 5 6
3 4 5 6 7 8 9 9
-------------
  9 9 8 7 6 5 4 3 2 1
[9 9 8 7 6 ][5 4 3 2 1]
[9 9 8][7 6][5 4 3][2 1]
[9 9]         [5 4]
9 9
8 9 9
6 7
6 7 8 9 9
4 5
3 4 5
1 2
1 2 3 4 5
1 2 3 4 5 6 7 8 9 9


你可能感兴趣的:(归并排序)