Efficiency is important. Here's a better way to find the length of an array.

in humor •  7 years ago 
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Not recursive enough, would suggest optimisation.

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.

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.

Image Transcription:


[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;
}

^^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!