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

java實現歸併排序演算法

前面我們講了歸併排序演算法,接下來我們來用java程式碼實現唄,如下

package ttt;

import java.util.Arrays;

public class MergeSort {
	public static int[] lastMergeSort(int[] list1,int[] list2) {
	    int i = 0, j = 0, k = 0;
	    int [] temp = new int[list1.length + list2.length];
	    while (i < list1.length && j < list2.length) {
	    	if (list1[i] <= list2[j]) {
	            temp[k++] = list1[i++];
	    	}else {
	        	temp[k++] = list2[j++];
	        }
	    }
	    
    	if (i == list1.length) {
    		while(j <list2.length) {
    			temp[k++] = list2[j++];
    		}
	    }
    	if (j == list2.length) {
    		for(;i <list1.length;)
    			temp[k++] = list1[i++];    		
	    }
	    return temp;
	}
	
    public static int[] mergeSort(int[] theArray) {
    	if(theArray.length ==1) {
    		return theArray;
    	}
    	int mid = (int)theArray.length/2;
    	int[] leftArray = mergeSort(Arrays.copyOfRange(theArray, 0, mid));//前閉後開區間,這種寫法開閉了很多空間,有點浪費,實則可以通過別的寫法避免的
    	int[] rightArray = mergeSort(Arrays.copyOfRange(theArray, mid, theArray.length));
    	return lastMergeSort(leftArray, rightArray);
    }

    public static void main(String[] args) {
    	int []theArray = {10,1,18,30,23,12,7,5,18,17};
        System.out.print("之前的排序:");
        for(int i = 0; i < theArray.length; i++) {
            System.out.print(theArray[i] + " ");
        }
        int [] larray = {1,4,10};
        int [] rarray = {2,6,8,11,15,18};
//        int []result_array = lastMergeSort(larray,rarray);
        int []resultArray = mergeSort(theArray);
        System.out.print("歸併排序:");
        for(int v : resultArray) {
            System.out.print(v + " ");
        }
    }
}

執行結果如下

之前的排序:10 1 18 30 23 12 7 5 18 17 歸併排序:1 5 7 10 12 17 18 18 23 30 

符合預期