如何合并和打印两个排序的整数数组

时间:2019-04-13 01:25:18

标签: java arrays sorting merge mergesort

我正在尝试创建一个方法,该方法接受两个已排序的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;
    }
}

1 个答案:

答案 0 :(得分:3)

您的代码中存在多个问题:

  • 您应该使用单独的方法进行测试,在arr1方法中分配arr2merge会达到目的。
  • 您必须为目标数组使用单独的索引。
  • 当到达任一数组的末尾时,您应该停止比较元素
  • 您应单独处理其余元素。

这是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个整数),从而对垃圾收集器造成不必要的压力。为整个合并排序使用单个临时数组会效率更高,但需要使用不同的merge方法。

相关问题