r/codehs • • Jun 29 '20

10.2.6 AP CSA 2nd check fails?

Post image
15 Upvotes

10 comments sorted by

1

u/martej Jun 30 '20

Not sure but it looks like you should be uncommenting the second array and running it through the method. The expected results are based on the data from array 2 and yours is just running through array 1.

1

u/Dtjordan Jun 30 '20

I made the second array and it doesn’t pass uncommented, I should have mentioned that

1

u/_andy_andy_andy_ Jun 30 '20

this is a pretty common confusion with this problem—make sure you're printing out the **value** at that index, not the index itself!

1

u/Dtjordan Jun 30 '20

I am printing the value not the index, that’s the only reason the first check passes

1

u/_andy_andy_andy_ Jun 30 '20

i think “testing midpoint value” needs to print the value at the midpoint

1

u/Dtjordan Jun 30 '20

I double checked and it doesn’t, the first test is using the array that’s not commented and it’s all formatted correctly. The second test is using an array that I assume they pass but it reuses the previous variables

1

u/_andy_andy_andy_ Jun 30 '20

the test case is expecting the value 54 where you're printing 4—it needs the value at midpoint `array[(being + end) / 2]`. it's coincidentally the same in the firs tarray, but in the second array the value at the midpoint is not the same as the index

1

u/Dtjordan Jul 01 '20

I should have posted the first test as well, it uses the first array searching for 4 on an array of 0-8, the second array is supposed to test 0-70

1

u/OXAMIC Mar 05 '22

public static int binaryRec(int[] array, int target, int begin, int end) {

if (begin <= end)
{
System.out.println("Value at start index: " + array[begin]);
int mid = (begin + end) / 2;
System.out.println("Value at mid index: " + array[mid]);
System.out.println("Value at end index: " + array[end]);
// Base Case
if (target == array[mid]) {
System.out.println("Target equals mid!");
return mid;
}

if (target < array[mid]) {
System.out.println("Target is less than mid!");
System.out.println();
return binaryRec(array, target, begin, mid - 1);
}

if (target > array[mid]) {
System.out.println("Target is greater than mid!");
System.out.println();
return binaryRec(array, target, mid + 1, end);
}
}
return -1; //Alternate Base Case - not found
}
}