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
你能舉一個我們可以運行的例子來證明這個問題和你期望得到的嗎? –