30/04/2021

[Java] Binary search on array

While doing another exercise, I needed to use binary search on an array and I realised I never published any code for that.


Let's remedy this. Important things to remember: array MUST be sorted, if not the logic makes no sense, finally the magic formula:

int mid = floor + ((ceil - floor) / 2);

Burn it in your mind and you'll forever be good to go. 

That's necessary because we alternate between sections of the array, so we won't always start from floor at position 0 and therefore need to offset our starting position everytime to the new floor.


Also I was checking how to make it generic, the change would simply be to modify the declaration of the method to:

 public static <T> int binarySearch(T[] elements, T element)  

And then invoke as:

 ArrayUtils.<TYPE>binarySearch(collection, element)  


However, since you are comparing elements in the collection, your generic type MUST offer the compareTo method to be used in place of integer comparison.


You can find my implementation of binarySearch for integer arrays on my Gist along with some tests in BinarySearchJTests.
An iterative version is proposed in binarySearchIterative along with some tests in BinarySearchIterativeJTests.

No comments:

Post a Comment

With great power comes great responsibility