commons-lang icon indicating copy to clipboard operation
commons-lang copied to clipboard

Add ArrayUtils.binarySearch() with a key extractor

Open kvr000 opened this issue 1 year ago • 5 comments

There is Collections.binarySearch() in Java core. However, it searches for exact element which is often not usable, as the elements are typically sorted by particular field.

These methods introduce binarySearch() on arrays and (sorted) List, with ability to provide sorting key extraction function and key comparator.

The rest of semantics, behavior, parameters and return values remain consistent with Collections.binarySearch() from Java core.

kvr000 avatar Aug 31 '24 19:08 kvr000

Hello @kvr000,

This code should be in ArrayUtils. TY!

@garydgregory : Yeah, got it, was busy to finish that. Fixed now, thank you.

kvr000 avatar Sep 11 '24 04:09 kvr000

Hello @kvr000, This code should be in ArrayUtils. TY!

@garydgregory : Yeah, got it, was busy to finish that. Fixed now, thank you.

@kvr000

Run mvn (by itself) before you push to catch build errors.

garydgregory avatar Sep 11 '24 13:09 garydgregory

Hello @kvr000

  • See my scattered comments.
  • Add a method called createSortedList(int...) that guarantees sorted results and use it.
  • Add tests for non-sorted input, make sure the results are predictable, we do not want a DOS for an infinite loop for example.

@garydgregory :

The createdSortedList() won't have any value. In the test, I have to see what is returned index - that's impossible with unsorted array. Additionally, now it's used also for intentionally unsorted array.

Good point for non-sorted input, I added a test. The code always does l = m+1 or h = m-1 , so it's safe.

kvr000 avatar Sep 12 '24 02:09 kvr000

@kvr000 Please revert the First/Last APIs.

garydgregory avatar Sep 13 '24 14:09 garydgregory

@kvr000 Please revert the First/Last APIs.

@garydgregory : As explained in https://github.com/apache/commons-lang/pull/1270/#discussion_r1759171390 , I want to keep First/Last as I find them more useful due to their predictability. I don't think we really need original unpredictable simple binarySearch.

kvr000 avatar Sep 18 '24 03:09 kvr000