diff --git a/libraries/stdlib/src/kotlin/collections/Collections.kt b/libraries/stdlib/src/kotlin/collections/Collections.kt index f49586206b28b..bfbabb14cc10d 100644 --- a/libraries/stdlib/src/kotlin/collections/Collections.kt +++ b/libraries/stdlib/src/kotlin/collections/Collections.kt @@ -350,8 +350,6 @@ public fun > List.binarySearch(element: T?, fromIndex: Int * * If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found. * - * `null` value is considered to be less than any non-null value. - * * @return the index of the element, if it is contained in the list within the specified range; * otherwise, the inverted insertion point `(-insertion point - 1)`. * The insertion point is defined as the index at which the element should be inserted, @@ -403,9 +401,23 @@ public inline fun > List.binarySearchBy( ): Int = binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) } -// do not introduce this overload --- too rare -//public fun List.binarySearchBy(key: K, comparator: Comparator, fromIndex: Int = 0, toIndex: Int = size(), selector: (T) -> K): Int = -// binarySearch(fromIndex, toIndex) { comparator.compare(selector(it), key) } +/** + * Searches this list or its range for an element having the key returned by the specified [selector] function + * equal to the provided [key] value using the binary search algorithm. + * The list is expected to be sorted into ascending order according to the ordering of keys of its elements as given by the specified [comparator]. + * otherwise the result is undefined. + * + * If the list contains multiple elements with the specified [key], there is no guarantee which one will be found. + * + * @return the index of the element with the specified [key], if it is contained in the list within the specified range; + * otherwise, the inverted insertion point `(-insertion point - 1)`. + * The insertion point is defined as the index at which the element should be inserted, + * so that the list (or the specified subrange of list) still remains sorted. + * @sample samples.collections.Collections.Lists.binarySearchByKey + * @sample samples.collections.Collections.Lists.binarySearchWithComparator + */ +public fun List.binarySearchBy(key: K, comparator: Comparator, fromIndex: Int = 0, toIndex: Int = size, selector: (T) -> K): Int = + binarySearch(fromIndex, toIndex) { comparator.compare(selector(it), key) } /**