Kotlin Comparable Binary Search for Object List

In the tutorial, JavaSampleApproach will show you how to look up an element in an object list with Kotlin Comparable Binary Search.

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

I. Technologies

– Kotlin 1.1.61
– Java 8

II. Kotlin Comparable Binary Search

With Comparable Binary Search, We need prepare a sorted Comparable object list, so:

Step to do
– Implement Comparable data model
– Create a sorted list
– Do Binary Search

1. Implement Comparable data model

2. Create a sorted list

We can use Iterable.sorted() to sort a Comparable Object List.
-> Detail method signature: public fun> Iterable.sorted(): List

More at: Kotlin – Sort List of Objects with Comparable

3. Comparable Binary Search

We use below method signature for Comparable Binary Search:

The Comparable Binary Search will search the sorted list or its range for the provided element using the binary search algorithm.
It will return the index of given element. Otherwise, it will return the inverted insertion point (-insertion point – 1).

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 grokonez | December 14, 2017.

Related Posts

Got Something To Say:

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