算法 - 兩個有序數組合並成一個有序數組


    //兩個有序數組的合並函數
    public static int[] MergeList(int a[],int b[])
    {
        int result[];  
        if(checkSort(a) && checkSort(b))  //檢查傳入的數組是否是有序的
        {
            result = new int[a.length+b.length];
            
            int i=0,j=0,k=0;   //i:用於標示a數組    j:用來標示b數組  k:用來標示傳入的數組

            while(i<a.length && j<b.length)
                if(a[i] <= b[j]) {
                    result[k++] = a[i++];
                }else{
                    result[k++] = b[j++];
                }

            /* 后面連個while循環是用來保證兩個數組比較完之后剩下的一個數組里的元素能順利傳入 */
            while(i < a.length) 
                result[k++] = a[i++];
            while(j < b.length)
                result[k++] = b[j++];
            
            return result;
        }
        else 
        {
            System.out.print("非有序數組,不可排序!");
            return null;
        }
    }
    
    //檢查數組是否是順序存儲的
    public static boolean checkSort(int a[])
    {
for(int j=i+1; j<a.length; j++)
                if(a[j-1] > a[j])
                    return false;
        }
        return true;        
    }
    
    // 打印函數
    public static void print(int b[])
    {
         for(int i=0; i<b.length ; i++)
         {
             System.out.print(b[i] + (i%10 ==9 ? "\n":"\t"));
         }
    }
    
    public static void main(String args[])
    {
        int a[]={1,2,2,3,5,6,7,7};
        int b[]={1,2,4,5,8,8,9,10,11,12,12,13,14};
        int c[]= MergeList(a,b);
        if(c!=null)
        print(c);
        else
            System.out.println("");
    }
}

 


免責聲明!

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



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