gpt4 book ai didi

java - 合并排序java实现错误

转载 作者:行者123 更新时间:2023-11-30 06:14:03 25 4
gpt4 key购买 nike

好的,所以我尝试在 java 中实现合并排序,但在拆分数组时遇到以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: 2 > 1
at java.util.Arrays.copyOfRange(Arrays.java:3591)
at MergeSortS.recMergeSort(MergeSortS.java:26)
at MergeSortS.recMergeSort(MergeSortS.java:28)
at MergeSortS.mergeSort(MergeSortS.java:17)
at MergeSortM.main(MergeSortM.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

我的代码段如下,请帮我找出我的问题...:(我特意在最后注释掉了 recMergeSort(right) 递归调用,因为我想更正 recMergeSort(left) 调用...

public void recMergeSort(int[] tempArray){
if(tempArray.length>1){
int mid=(tempArray.length)/2;

int[] left=Arrays.copyOfRange(tempArray,0,mid);

int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length-1);

recMergeSort(left);
//recMergeSort(array, right, mid+1, right.length-1);
}
}

编辑好的,所以我检查了另一个站点和 javadoc 上的 copyOfRange 方法,需要以下内容:

Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)

修复后如下:

public void recMergeSort(int[] tempArray){
if(tempArray.length>1){
int mid=(tempArray.length)/2;

int[] left=Arrays.copyOfRange(tempArray,0,mid+1);

int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length);

recMergeSort(left);
//recMergeSort(array, right, mid+1, right.length-1);
}
}

我收到以下错误:

Exception in thread "main" java.lang.StackOverflowError

请帮我解决这个问题...:(

最佳答案

您似乎陷入了 Arrays.copyOfRange() 方法的困境。请尝试使用此代码:

public void recMergeSort(int[] tempArray){
if (tempArray.length > 1 ){
int mid=(tempArray.length)/2; // mid = 2
int[] left = Arrays.copyOfRange(tempArray, 0, mid); // [10, 20]
int[] right = Arrays.copyOfRange(tempArray, mid, tempArray.length); // [30, 40, 50]

recMergeSort(left);
//recMergeSort(array, right, mid+1, right.length-1);
}
}

Arrays.copyOfRange(array, lowIndex, highIndex) 将从lowIndex inclusivehighIndex 复制访问> 独家。这意味着左侧副本的 highIndex 应该与右侧副本的 lowIndex 相同

用法:

int[] tempArray = new int[] {10, 20, 30, 40, 50};
recMergeSory(tempArray);

关于java - 合并排序java实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31019683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com