private static void split(int arr[], int low, int high){
int[] newArr = arr;
//Split num of coins into 3 sub arrays
int mid1 = (int) Math.floor((low+high)/3);
int mid2 = (int) Math.floor((low+high)/1.5);
for(int i=0; i<= high; i++){
System.out.print("newArr:"+newArr[i]+", ");
}
System.out.print("mid1:"+mid1+" mid2:"+mid2+"\n");
int[] a = new int[mid1+1];
int[] b = new int[mid1+1];
int[] c = new int[mid1+1];
int i, j, k;
for(i=0; i<= mid1; i++){ //1,2,3
a[i] = arr[i];
System.out.println("a"+a[i]);
}
i=0;
for(j=mid1+1; j<=mid2; j++){ //4,5,6
b[i] = arr[j];
System.out.println("b"+b[i]);
i++;
}
i=0;
for(k=mid2+1; k<=high; k++){ //7,8,9
c[i] = arr[k];
System.out.println("c"+c[i]);
i++;
}
System.out.print("a: ");
for(i=0;i<a.length;i++){
System.out.print(a[i]+", ");
}
System.out.print("b: ");
for(i=0;i<b.length;i++){
System.out.print(b[i]+", ");
}
System.out.print("c: ");
for(i=0;i<c.length;i++){
System.out.print(c[i]+", ");
}
System.out.println("");
//Compare
int sumA=0, sumB=0;
for(i=0; i<a.length; i++){
sumA += a[i];
}
System.out.println("sumA:"+sumA);
for(j=0; j<b.length; j++){
sumB += b[j];
}
System.out.println("sumB:"+sumB);
if(sumA > sumB){
//check if element is last coin in arr
if(a.length == 1){
System.out.print("You've found the coin in a!");
} else {
//split a
System.out.println("split a: ");
split(a, a[0], a[a.length - 1]);
}
}
else if(sumB > sumA){
//check if element is last coin in arr
if(b.length == 1){
System.out.print("You've found the coin in b!");
} else {
//split b
System.out.println("split b: ");
System.out.print("b: ");
for(i=0;i<b.length;i++){
System.out.print(b[i]+", ");
}
split(b, b[0], b[b.length-1]);
}
}
else{
//check if element is last coin in arr
if(c.length == 1){
System.out.print("You've found the coin in c!");
} else {
//split orig last 3
System.out.println("split c: ");
split(c, c[0], c[c.length - 1]);
}
}
}
我的原始数组= = int [] arr = {0,0,0,0,1,0,0,0,0}; 我试图找到价值之一。一旦它通过split函数,值0,1,0将在数组b中,因此它将再次调用split,但是当您在split中检查newArr时,它只有0值,而不是0,1 ,0。为什么我的元素消失。Java - 传递一个数组,但它正在丢弃元素
P.S有很多打印语句,我一直在试图弄清楚为什么它没有抓住第一次运行和第二次运行之间的所有元素,抱歉。
如果您包含您正在调用此特定方法的参数,那么这将有助于您获得答案。也就是说,包括你的'main'方法和任何用来调用这个方法的辅助方法。 – Makoto
当mid2> high或mid1
你能举一个我们可以运行的例子来证明这个问题和你期望得到的吗? –