归并排序

import java.math.* ;
import java.util.* ;

/**
 * 
 */
public class Test extends Base{
	public static void main(String[] args) throws Exception{
		int[] arr = getRandomArr() ;
		println(arr); 
		int[] temp = new int[arr.length] ;
		mergeSort(arr , arr.length);
		println(arr);
		println();		
	}

	public static void mergeSort(int[] arr , int n) throws Exception{
		int[] temp = new int[n] ;
		divideSort(arr, 0 , n - 1 , temp);
	}
	
	public static void divideSort(int[]arr , int first , int last , int[] temp) throws Exception{

		if(first <  last){
			divideSort(arr , first, (first + last) / 2 , temp);
			divideSort(arr , (first + last) / 2 + 1 , last , temp);
			mergeArray(arr, first , (first + last) / 2 , last , temp);
		}	
	}

	public static void mergeArray(int[] arr ,int first, int mid , int last , int[] temp){
		int firstStart = first , firstEnd = mid ;
		int secondStart = mid + 1 , secondEnd = last ;
		int k = 0 ;
		while (firstStart <= firstEnd && secondStart <= secondEnd){
			if(arr[firstStart] < arr[secondStart])
				temp[k++] = arr[firstStart++] ;
			else 
				temp[k++] = arr[secondStart++] ;
		}
		while(firstStart <= mid)
			temp[k++] = arr[firstStart++] ;
		while(secondStart <= last)
			temp[k++] = arr[secondStart++] ;

		for (int i = 0; i < k ; i++ ){
			arr[first + i] = temp[i] ;
		}
	}

}

点赞