在合并等长的已排序数组时输出错误。

huangapple go评论71阅读模式
英文:

Wrong output while merging sorted arrays of equal length

问题

我正在尝试合并两个等长的已排序数组然而我没有得到期望的输出
下面是我的代码

```java
	public static int[] mergeSorted(int[] arr1, int[] arr2){
		int n = arr2.length;

		int[] ans = new int[2*n];

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

		while(i < n && j < n){
			if(arr1[i] <= arr2[j]){
				ans[k] = arr1[i];
				i++;
			}
			else{
				ans[k] = arr2[j];
				j++;
			}
			k++;
		}

		while(i < n){
			ans[k] = arr1[i];
			k++;
			i++;
		}

		while(j < n){
			ans[k] = arr2[j];
			k++;
			j++;
		}

		return ans;
	}

	public static void main(String[] args){
		int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};
		int[] arr2 = new int[]{2, 4, 6, 9, 13, 300};

		int[] ans = mergeSorted(arr1, arr2);

		for(int el : ans)
			System.out.print(el + " ");
	}

输出:

1 2 3 4 5 6 9 13 100 34 29 300

显然,这是不正确的。然而,这段代码适用于更小的输入。我在哪里出错了?

编辑:测试用例错误,因为它们没有排序。代码是正确的。


<details>
<summary>英文:</summary>
I&#39;m trying to merge 2 sorted arrays of equal length. However, I&#39;m not getting the desired output. 
Here is my code:
public static int[] mergeSorted(int[] arr1, int[] arr2){
int n = arr2.length;
int[] ans = new int[2*n];
int k = 0;
int i = 0;
int j = 0;
while(i &lt; n &amp;&amp; j &lt; n){
if(arr1[i] &lt;= arr2[j]){
ans[k] = arr1[i];
i++;
}
else{
ans[k] = arr2[j];
j++;
}
k++;
}
while(i &lt; n){
ans[k] = arr1[i];
k++;
i++;
}
while(j &lt; n){
ans[k] = arr2[j];
k++;
j++;
}
return ans;
}
public static void main(String[] args){
int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};
int[] arr2 = new int[]{2, 4, 6, 9, 13, 300};
int[] ans = mergeSorted(arr1, arr2);
for(int el : ans)
System.out.print(el + &quot; &quot;);
}

Output:
1 2 3 4 5 6 9 13 100 34 29 300
Clearly, this is not correct. However, this code works for smaller inputs. Where am I going wrong?
EDIT: Test cases were wrong as they were not sorted. Code was fine.
</details>
# 答案1
**得分**: 1
为了使`merge`操作正常工作,你要合并的两个数组应该是有序的。第一个数组并没有按照顺序排列:
```java
int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};

请修改为:

int[] arr1 = new int[]{1, 3, 5, 29, 34, 100};
英文:

For the merge operation to work, the two arrays you are merging should be in sorted order. The first array is not in sorted order:

    int[] arr1 = new int[]{1, 3, 5, 100, 34, 29};

Change it to:

    int[] arr1 = new int[]{1, 3, 5, 29, 34, 100};

huangapple
  • 本文由 发表于 2020年8月22日 22:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63537055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定