gpt4 book ai didi

java - mergeSort ArrayIndexOutOfBoundsExecption

转载 作者:行者123 更新时间:2023-11-30 02:24:39 26 4
gpt4 key购买 nike

练习合并排序时遇到问题。我在线程“main”java.lang.ArrayIndexOutOfBoundsException 中收到异常:1mergeSort 部分工作得很好,但重新组装数组对我来说很困难。任何帮助将不胜感激。

public class MyMergeSort {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arry1 = {42, 12, 30, 77, 590, 1};
int[] arry2 = mergeSort(arry1);
System.out.println("Merge Sort Demo: ");
for(int i:arry2){
System.out.print(i);
System.out.print(" ");
}
}

static int[] mergeSort(int[] arry1) {

int n = arry1.length;
if(n < 2)
return arry1;

int mid = n / 2;
int left[] = new int[mid];
int right[] = new int [n - mid];
for(int i = 0; i< mid; i++) {
left[i] = arry1[i];
}
for(int i = mid; i < n; i++) {
right[i - mid] = arry1[i];
}
mergeSort(left);
mergeSort(right);
merge(arry1, left, right);
return(arry1);
}

public static void merge(int[] arry1, int left[], int right[]){
int nL = left.length;
int nR = right.length;
int i = 0, j = 0, k= 0;

while( i < nL && j < nR) {
if(left[i] < right[j]){
arry1[k] = left[i];
i++;
} else {
arry1[k] = right[i];
j++;
}
k++;
}
while(i < nL) {
arry1[k] = left[i];
i++;
k++;
}
while(j < nR){
arry1[k] = right[i];
j++;
k++;
}
}
}

最佳答案

在你的合并方法中应该是这个 arry1[k] = right[j];

 public static void merge(int[] arry1, int left[], int right[]){
int nL = left.length;
int nR = right.length;
int i = 0, j = 0, k= 0;

while( i < nL && j < nR) {
if(left[i] < right[j]){
arry1[k] = left[i];
i++;
} else {
**arry1[k] = right[i];** // Why i it should be j
j++;
}
k++;
}
while(i < nL) {
arry1[k] = left[i];
i++;
k++;
}
while(j < nR){
**arry1[k] = right[i];** // Why i it should be j
j++;
k++;
}
}

我相信 j 是正确的,您正在增加 j 并仅对其有条件,但访问右侧的第 i 个索引而不是第 j 个索引。希望对您有帮助!

关于java - mergeSort ArrayIndexOutOfBoundsExecption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45948661/

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