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

歸併排序遞迴 java實現

package sort;


public class MergeSort1 {  
    /*** 歸併排序 
     * 簡介:將兩個(或兩個以上)有序表合併成一個新的有序表 即把待排序序列分為若干個子序列,每個子序列是有序的。然後再把有序子序列合併為整體有序序列 
     * 時間複雜度為O(nlogn) 穩定排序方式 
     */  
    public static int[] sort(int[] nums, int low, int high) {  
        int mid = (low + high) / 2;  
        if (low < high) {  
            // 左邊  
            sort(nums, low, mid);  
            // 右邊  
            sort(nums, mid + 1, high);  
            // 左右歸併  
            merge(nums, low, mid, high);  
        }  
        return nums;  
    }   
    public static void merge(int[] nums, int low, int mid, int high) {  
        int[] temp = new int[high - low + 1];  
        int i = low;// 左指標  
        int j = mid + 1;// 右指標  
        int k = 0;   
        // 把較小的數先移到新陣列中  
        while (i <= mid && j <= high) {  
            if (nums[i] < nums[j]) {  
                temp[k++] = nums[i++];  
            } else {  
                temp[k++] = nums[j++];  
            }  
        }   
        // 把左邊剩餘的數移入陣列  
        while (i <= mid) {  
            temp[k++] = nums[i++];  
        }    
        // 把右邊邊剩餘的數移入陣列  
        while (j <= high) {  
            temp[k++] = nums[j++];  
        }   
        // 把新陣列中的數覆蓋nums陣列  
        for (int k2 = 0; k2 < temp.length; k2++) {  
            nums[k2 + low] = temp[k2];  
        }  
    } 
//陣列列印函式
public static void printsort(int a[])
{
for(int k=0;k<a.length;k++)
System.out.println(a[k]);
}
     // 歸併排序的實現 
    public static void main(String[] args) {  
  
        int[] nums = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };  
  
        sort(nums, 0, nums.length-1);  
        printsort(nums);  
    }  
}