upper Bound
fun <T : Comparable<T>> List<T?>.upperBound(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int(source)
Returns the index of the first element in fromIndex..<toIndex that is greater than element, or toIndex if there is none. The range must be sorted in natural order with null first. O(log n).
Throws
Samples
val list = listOf(10, 20, 20, 20, 30, 40)
assertEquals(4, list.upperBound(20)) // just past the last of the equal elements
assertEquals(4, list.upperBound(25)) // absent: the same index as lowerBound
assertEquals(6, list.upperBound(50)) // greater than all: the size
assertEquals(3, list.upperBound(20) - list.lowerBound(20)) // 20 occurs three timesContent copied to clipboard
fun <T> List<T>.upperBound(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size): Int(source)
Returns the index of the first element in fromIndex..<toIndex that is greater than element by comparator, or toIndex if there is none. The range must be sorted by comparator. O(log n).
Throws
Samples
val list = listOf(11, 9, 7, 5, 3, 1)
val index = list.upperBound(7, reverseOrder())
assertEquals(3, index)
assertEquals(5, list[index])Content copied to clipboard
fun <T> List<T>.upperBound(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int(source)
Returns the index of the first element in fromIndex..<toIndex for which comparison is positive, or toIndex if there is none. Along the range comparison must be negative first, then zero, then positive, and any of these three parts may be empty. O(log n).
Throws
Samples
val list = listOf(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
val index = list.upperBound { it.compareTo(49) }
assertEquals(7, index)
assertEquals(64, list[index])Content copied to clipboard