Kotlin Binary Search for Object List with Comparison function – comparison: (T) -> Int

In the tutorial, JavaSampleApproach will show you how to look up an element in an object list with Kotlin Binary Search for Object List by Comparison function – comparison: (T) -> Int.

Related posts:
Kotlin Sort Object List with Kotlin Selector function – crossinline selector: (T) -> R?
Kotlin Comparator Binary Search for Object List
Kotlin Comparable Binary Search for Object List
Kotlin Binary Search for Object List with Selector function – crossinline selector: (T) -> K?

I. Technologies

– Kotlin 1.1.61
– Java 8

II. Kotlin Binary Search with Comparison function

Step to do:
– Create data model
– Create a sorted list
– Binary Search with Comparison function

1. Create data model

– Create Product data model:

Initial Product list:

2. Create a sorted list

We can use Iterable.sortedBy(crossinline selector: (T) -> R?) to sort an Object List.
-> Detail method signature:

So we need define a selector function:

Then do sorting Product List:

More at: Kotlin Sort Object List with Kotlin Selector function – crossinline selector: (T) -> R?

3. Binary Search with Comparison function

We use below method signature for Binary Search with Comparison function:

So We define an appropriate Comparison function as below:

Binary Search with Comparison function will search in the ascending sorted list or its range for an element for which [comparison] function returns zero using the binary search algorithm. It will return the index of given element. Otherwise, it will return the inverted insertion point (-insertion point – 1).

Note: The list is expected to be sorted into ascending order by [comparison] function. Otherwise, the result is undefined.

What is insertion point?
-> The insertion point is defined as the index at which the given element should be inserted for the list (or specified range of list) still remains sorted.

III. Full Sourcecode

By JavaSampleApproach | December 16, 2017.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*