JAVA排序之歸併排序

歸併排序思路就是不停拆分數組,直到拆成一個一個元素,以後將拆出來的元素按照拆分順序反過來的順序合併,出現前邊值大於後邊值,則換位置,放入臨時數組,最後將臨時數組覆蓋原數組.數組

public static int[] sort(int[] a,int low,int high){
        if(low<high){
            int mid = (low+high)/2;
            sort(a,low,mid);
            sort(a,mid+1,high);
            //左右歸併
            merge(a,low,mid,high);
        }
        return a;
    }
    
    public static void merge(int[] a, 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(a[i]<a[j]){
                temp[k++] = a[i++];
            }else{
                temp[k++] = a[j++];
            }
        }
        // 把左邊剩餘的數移入數組
        while(i<=mid){
            temp[k++] = a[i++];
        }
        // 把右邊邊剩餘的數移入數組
        while(j<=high){
            temp[k++] = a[j++];
        }
        // 把新數組中的數覆蓋nums數組
        for(int x=0;x<temp.length;x++){
            a[x+low] = temp[x];
        }
    }排序

相關文章
相關標籤/搜索