英文:
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'm trying to merge 2 sorted arrays of equal length. However, I'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 < 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 + " ");
}
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};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论