簡體   English   中英

如何合並和打印兩個排序的整數數組

[英]How to merge and print two sorted arrays of ints

我正在嘗試創建一個方法,該方法接收兩個已排序的int數組並返回一個新數組,該數組在不使用sort函數的情況下合並和調度這兩個列表。 我在循環中遇到麻煩,我不確定如何修復它。

我目前正在收到錯誤:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at pack8.Assignment8Code.merge(Assignment8Code.java:20)
    at pack8.Assignment8Code.main(Assignment8Code.java:39)

這是代碼:

public class Assignment8Code 
{   
    public static int[] merge(int[] arr1, int[] arr2)
    {
        //Create the first two arrays with testing numbers
        arr1 = new int[5];
        arr2 = new int[3];
        //Create a new array that will fit the length of the two given arrays
        int[] sortedArray = new int[(arr1.length + arr2.length)];
        //Create starting index values to check all arrays and merge
        int index1 = 0;
        int index2 = 0;

        //Test to see if the given arrays are populated
        while(index1 < arr1.length || index2 < arr2.length)
        {
            //Check to see which array starts with the higher number
            if(arr1[index1] < arr2[index2])
            {
                sortedArray[index1] = arr1[index1];
                index1++;
            }
            else
            {
                sortedArray[index2] = arr2[index2];
                index2++;
            }
        }
        return sortedArray;
    }
}

您的代碼中存在多個問題:

  • 你應該使用一個單獨的方法進行測試,在merge方法中分配arr1arr2會使其失敗。
  • 您必須為目標數組使用單獨的索引。
  • 當你到達任一陣列的末尾時,你應該停止比較元素
  • 你應該分開處理剩余的元素。

以下是merge方法的更正版本:

public class Assignment8Code 
{   
    public static int[] merge(int[] arr1, int[] arr2)
    {
        // Allocate a new array that will fit the length of the two given arrays
        int[] sortedArray = new int[(arr1.length + arr2.length)];

        int index1 = 0;
        int index2 = 0;
        int index3 = 0;

        // Merge the sorted arrays
        while (index1 < arr1.length && index2 < arr2.length)
        {
            //Check to see which array starts with the higher number
            if (arr1[index1] <= arr2[index2])
            {
                sortedArray[index3++] = arr1[index1++];
            }
            else
            {
                sortedArray[index3++] = arr2[index2++];
            }
        }
        // Append the remaining elements 
        while (index1 < arr1.length)
        {
            sortedArray[index3++] = arr1[index1++];
        }
        while (index2 < arr2.length)
        {
            sortedArray[index3++] = arr2[index2++];
        }
        return sortedArray;
    }
}

請注意,這種方法效率很低,因為它為每個合並分配了一個新數組。 以這種方式為大型數組實現mergesort將分配大量的mmemory(log2(N)* N整數),從而對垃圾收集器造成不必要的壓力。 對整個mergesort使用單個臨時數組會更有效,但需要不同的merge方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM