1. 程式人生 > >歸併排序java實現

歸併排序java實現

package algorithm;

public class MergeSort {
	public static void main(String[] args) {
		int[] a = {2,4,7,9,6,1,3,8};
		int L = 0;
		int R = 7;
		mergeSort(a, L, R);
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
	private static void merge(int[] a, int L, int M, int R){
		int left_size = M -L;
		int right_size = R - M +1;
		int[] left  = new int[left_size];
		int[] right = new int[right_size];
		
		
		//填充左邊的陣列
		for(int i = L; i < M; i++){
			left[i - L] = a[i];
		}
		
		//填充右邊的陣列
		for(int i = M; i <= R; i++){
			right[i - M] = a[i];
		}
		
		//合併到原來的陣列中
		int i = 0, j = 0,k = L;
		while(i < left_size && j < right_size){
			if(left[i] < right[j]){
				a[k] = left[i];
				i++;
				k++;
			}else{
				a[k] = right[j];
				j++;
				k++;
			}
		}
		
		while(i < left_size){
			a[k] = left[i];
			i++;
			k++;
		}
		
		while(j < right_size){
			a[k] = right[j];
			j++;
			k++;
		}
		
	}
	
	private static void mergeSort(int[] a, int L, int R){
		if(L ==R){
			return;
		}else{
			int M = (L + R) /2;
			//歸併排序左半部分
			mergeSort(a, L, M);
			//歸併排序右半部分
			mergeSort(a, M+1, R);
			//將左右兩個部分合二為一
			merge(a, L, M+1, R);
		}
	
	}

}