排序算法Java代碼實現(四)—— 歸並排序


本篇內容:

  • 歸並排序

 

歸並排序

算法思想:

將兩個或兩個以上的有序表合並成一個新的有序表,

即把待排序序列分成若干個子序列,每個子序列是有序的,然后在把有序子序列合並為整體有序序列.

此算法分為兩步:

(1)把數組等長切分;

(2)把切分后的數組進行排序,然后合並;

通過切分方法的遞歸調用,可以將數組切分到最小(2個元素)的組合;

代碼:

(1)合並兩個數組的方法:

//將兩個數組合並
    public static void Merge(int[] array,int low,int mid,int high)
    {
        int[] temp = new int[high-low+1];
        int pLeft = low;
        int pRight = mid+1;
        int k = 0;
        //先把較小的數移到新數組中
        while(pLeft <= mid&&pRight <= high)
        {
            if(array[pLeft]<array[pRight])
            {
                temp[k++] = array[pLeft++];
            }else
            {
                temp[k++] = array[pRight++];
            }
        }
        //把左邊剩余的數移到新數組中
        while(pLeft <= mid)
        {
            temp[k++] = array[pLeft++];
        }
        //把右邊剩余的數移入新數組
        while(pRight <= high)
        {
            temp[k++] = array[pRight++];
        }
        //用新數組中的數覆蓋array數組
        for(int i = 0;i < temp.length ; i++)
        {
            array[i+low] = temp[i];
        }    
        printArray(array);
    }

 

(2)自頂向下合並數組

/*
     * 將兩個或兩個以上的有序表合並成一個新的有序表
     * 即把待排序序列分成若干個子序列,每個子序列是有序的,然后在把有序子序列合並為整體有序序列
     * */
    public static void MergeSorting(int[] array,int low,int high)
    {
        if(low == high)
        {
            return;
        }
        int mid = (low + high)/2;
        if(low<high)
        {
            //對左邊排序
            MergeSorting(array,low,mid);
            //對右邊排序
            MergeSorting(array,mid+1,high);
            //左右合並
            Merge(array,low,mid,high);
        }
    }

 

實現結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM