归并排序

当一个需要排序的数组前后两部分为排好序的时候,我们就会用到归并排序,即把前后两个数组合为一个排好序的数组,如果不是前后两部分排好序的,则用分治法使其前后两部分排好序,代码如下:

/*
 * merge sort
 * @Author: lvlang1993
 * */
public class MergeSort {
	public static void main(String[] args) {
		int arr[] = {6, 1, 4, 3, 8, 5, 48, 10};;

		mergeSort(arr, 0, arr.length - 1);
		System.out.println("mergeSort test");
		for(int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}
    
    /*
	 * merge sort by making recurisive calls
	 * @Param: arr, the array to be sorted
	 * @Param: lt, the left begin index
	 * @Param: rt, the right end index
	 * @Return
	 * */
	public static void mergeSort(int arr[], int lt, int rt) {
		if(lt == rt) {
			return ;
		}
		else {
			int mid = (lt + rt) / 2;
			mergeSort(arr, lt, mid);//merge sort the left subarray
			mergeSort(arr, mid + 1, rt);//merge sort the right subarray
			merge(arr, lt, mid + 1, rt);//merge the array after the left and right subarray sorted
		}
	}
    
    /*
	 * merge two sorted halves of a subarray
	 * @Param: arr, the array to be sorted
	 * @Param: beginIndex, the begin index
	 * @Param: middleIndex, the middle index
	 * @Param: endIndex, the end index
	 * @Return
	 * */
	public static void merge(int arr[], int beginIndex, int middleIndex, int endIndex) {
		//split arr into arrLeft and arrRight
		int arrLeftSize = middleIndex - beginIndex;
		int arrRightSize = endIndex - middleIndex + 1;
		int arrLeft[] = new int[arrLeftSize];
		int arrRight[] = new int[arrRightSize];

		for(int i = beginIndex; i < middleIndex; i++) {
			arrLeft[i - beginIndex] = arr[i];
		}
		for(int i = middleIndex; i <= endIndex; i++) {
			arrRight[i - middleIndex] = arr[i];
		}
        
        //compare the arrLeft and arrRight val, then put the min one into the arr
		int x = 0, y = 0, z = beginIndex;//two subarrays index and the arr index
		while(x < arrLeftSize && y < arrRightSize) {//under the size
			if(arrLeft[x] < arrRight[y]) {
				arr[z] = arrLeft[x];
				x++;
				z++;
			}
			else {
				arr[z] = arrRight[y];
				y++;
				z++;
			}
		}

        //after the arrRight all in the arr but arrLeft isn't
		while(x < arrLeftSize) {
			arr[z] = arrLeft[x];
			x++;
			z++;
		}

        //after the arrLeft all in the arr but arrRight isn't
		while(y < arrRightSize) {
			arr[z] = arrRight[y];
			y++;
			z++;
		}
	}
}
点赞