【问题标题】:Can any one give me better solution for merging two sorted arrays into another sorted array [duplicate]谁能给我更好的解决方案来将两个排序数组合并到另一个排序数组中[重复]
【发布时间】:2017-06-16 15:17:36
【问题描述】:
public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arrA = {2,3,4};
        int[] arrB = {5,6,7,8};
        mergeArray(arrA,arrB);
    }
    static void mergeArray(int[] arrA,int[] arrB){

        int len = arrA.length+arrB.length;
        int lenA = arrA.length;
        int lenB = arrB.length;
        int a=0,b=0,c=0;
        int temp=0;
        int[] arrC = new int[len];
        for(int i=0; i < lenA; i++){
            arrC[i] = arrA[i];
        }
        for(int j=lenA,k=0; (k < lenB) && (j < len) ; j++,k++){
            arrC[j] = arrB[k];
        }
        for(int n=0; n < len ; n++){
            for(int m=0; m < len; m++ ){
                if(arrC[n] < arrC[m]){
                    temp  = arrC[n];
                    arrC[n] = arrC[m];
                    arrC[m] = temp;
                }
            }
        }
        for(int x : arrC){
            System.out.println(x);
        }
    }

结果:{2,3,4,5,6,7,8}

我正在尝试将值放入一个新数组并再次对其进行排序。谁能给我比这更好的解决方案。

【问题讨论】:

  • 这个有什么问题?
  • 我想要比这个更好的解决方案。@beaker
  • 看看System#arrayCopy
  • 有没有不使用库方法的解决方案?? @JonK
  • 一个显而易见的改进:让你的 mergeArray 方法实际返回新的合并数组,而不是什么都不做,这样它很快就会遇到垃圾收集器。

标签: java arrays algorithm sorting


【解决方案1】:

我想起了旧时的学生时代!这是解决方案!没有库,只有简单的代码!享受吧。

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int [] array1 = {5, 1, 4, 5, 7, 8, 1, 0, 4};
        int [] array2 = {4, 7, 1, 0, 9, 3};

        System.out.println("Array 1");
        print(array1);

        System.out.println("Array 2");
        print(array2);

        Arrays.sort(array1);
        Arrays.sort(array2);

        System.out.println("Sorted array 1");
        print(array1);

        System.out.println("Sorted array 2");
        print(array2);

        int [] mergedAndSortedArray = mergeSorted(array1, array2);

        System.out.println("Sorted merged array");
        print(mergedAndSortedArray);
    }

    private static void print(int [] array) {
        for (int i : array) {
            System.out.print(i + " ");
        }

        System.out.println("\n");
    }

    private static int [] mergeSorted(int [] array1, int [] array2) {
        int [] res = new int [array1.length + array2.length];

        int i = 0;
        int j = 0;
        int k = 0;

        //Do your homework. First loop until you reach end of either array, and then add the rest elements.

        return res;
    }
}

这是结果

Array 1
5 1 4 5 7 8 1 0 4 

Array 2
4 7 1 0 9 3 

Sorted array 1
0 1 1 4 4 5 5 7 8 

Sorted array 2
0 1 3 4 7 9 

Sorted merged array
0 0 1 1 1 3 4 4 4 5 5 7 7 8 9 

更新

如果您需要将 N 个已排序的数组合并为一个已排序的数组,您可以递归地成对合并它们(合并第一个和第二个数组,第三个和第四个,依此类推),然后再一次,直到你有两个数组,最后也合并它们!

【讨论】:

  • How do I ask and answer homework questions“如果您认为这对学生没有帮助,最好不要提供完整的代码示例,使用您的最佳判断。”
  • 另外,不鼓励使用“+1”cmets。
  • 您创建了第二个答案,而不是编辑这个。
  • 每个用户一个适当的答案就足够了。
  • @AndyThomas 好的,我删除了第二个答案。我删除了作业解决方案,只是用文字解释了这个想法。说到作业,其他一些答案可以复制粘贴。
【解决方案2】:

您可以使用 Java8 流:

    int[] arrA = {2,3,4};
    int[] arrB = {5,6,7,8};
    int[] mergedArray = IntStream.concat(Arrays.stream(arrA), Arrays.stream(arrB)).toArray();

如果顺序很重要:

IntStream.concat(Arrays.stream(arrA), Arrays.stream(arrB)).sorted().toArray();

在这种情况下,您不仅可以将其转换为数组,还可以转换为您想要的任何内容。

【讨论】:

    【解决方案3】:

    简单。您正在连接一个又一个数组,然后进行冒泡排序。在最坏的情况下,冒泡排序是 O(n^2)。这意味着排序所需的时间可能会随着两个输入数组长度之和的平方而增加。

    但是你已经知道这两个数组是有序的。写入组合数组时,您只需要查看两个输入数组的头部即可。下一次写入将是两者中的最小值。您的合并将是 O(n),其中 n 是两个输入数组的长度之和。

    这是称为merge sort 的排序算法的一部分。合并排序通常是就地的,在单个数组中。你的略有不同,两个排序部分在不同的数组中,但想法是一样的。

    【讨论】:

      【解决方案4】:

      试试这个:

      Integer[] mergeArray = (Integer[])ArrayUtils.addAll(arrA, arrB);
      

      看看这个:

      public static T[] addAll(T[] array1, T... array2)

      然后:

      Arrays.sort(mergeArray, Collections.reverseOrder());
      

      【讨论】:

      • 我认为 OP 想要一个有效的合并排序,这样 [1,3,5][2,4,6] 合并到 [1,2,3,4,5,6]
      • 为什么要将整数值转换为字符串?
      【解决方案5】:

      我认为您正在寻求一种将两个已排序的数组“压缩在一起”的方法,以便最终得到一个已排序的数组。我想你已经意识到连接然后排序是低效的,因为它没有利用已经排序的输入数组。

      我还假设这是一个家庭作业或学习问题,所以我将在高层次上描述解决方案。

      您需要一些变量来跟踪您的位置:

      • leftIndex(您在左侧输入的位置)
      • rightIndex(您在右侧输入的位置)
      • destinationIndex(您在目的地的位置)

      从零开始所有索引。现在我们要选择一个数组来工作,并从中一个一个地取值。

      只要这些值小于另一个输入数组中的下一个值,我们就会将其添加到输出中。然后我们切换到另一个数组。我们不断来回切换,直到我们到达两个输入的末尾。

      伪代码:

      while (leftIndex and rightIndex are both within the length of their arrays) {
          while(leftInput[leftIndex] is less than rightInput[rightIndex]) {
               copy leftInput[leftIndex] into destination[destinationIndex]
               increment leftIndex
               increment destinationIndex
          }
          while(rightInput[rightIndex] is less than leftInput[leftIndex]) {
               copy rightInput[leftIndex] into destination[destinationIndex]
               increment rightIndex
               increment destinationIndex
          }
      }
      

      如果你将我写的内容直接翻译成 Java,你可能会得到ArrayIndexOutOfBounds 异常。您需要在 while 语句中添加额外的代码,以使其在其中一个索引超出其数组末尾时执行正确的操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多