Could it be that youve got the adaptions if min and max exactly the wrong way round? If you get an exception the array has less than mid elements and max should then be mid.
[Screenshot of a function which returns the length of an array]
public static int arrayLength(int[] arr) {
int min = 0;
int max = Integer.MAX_VALUE;
while (min + 1 < max) {
int mid = (min + max) / 2;
try {
int elem = arr[mid];
max = mid - 1;
} catch (ArrayIndexOutOfBoundsException e) {
min = mid + 1;
}
}
return min;
}
As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Not recursive enough, would suggest optimisation.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Now I'm thinking about if there even is a way to find out the length besides .Length and catching OutOfRangeExceptions.
PS: I think reflection should work to to read the private length field.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Could it be that youve got the adaptions if min and max exactly the wrong way round? If you get an exception the array has less than mid elements and max should then be mid.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Image Transcription:
[Screenshot of a function which returns the length of an array]
^^I'm a human volunteer content transcriber for Reddit! If you'd like more information on what we do and why we do it, click here!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit