Scoop API

scoop:scoop.std:0.1.0

src/collections/binary_search.scoop

Selected production source · src/collections/binary_search.scoop

1package scoop.collections
3import scoop.comparisons.Comparator
4import scoop.comparisons.naturalOrder
6/**
7 * Searches a range sorted by the same ordering. The range is fromIndex inclusive to toIndex
8 * exclusive; absence returns -(insertionIndex + 1).
9 */
10public fun <T> List<T>.binarySearch(
11 element: T, comparator: Comparator<T>, fromIndex: Long = 0L, toIndex: Long = this.size
12): Long {
13 if (fromIndex > toIndex) throw IllegalArgumentException(Some("reversed search range"))
14 if (fromIndex < 0L || toIndex > size || fromIndex > size || toIndex < 0L) throw IndexOutOfBoundsException()
15 var low = fromIndex
16 var high = toIndex
17 while (low < high) {
18 val middle = low + (high - low) / 2L
19 val compared = comparator.compare(this[middle], element)
20 if (compared == 0L) return middle
21 if (compared < 0L) low = middle + 1L else high = middle
22 }
23 return -low - 1L
26/**
27 * Searches a range sorted by the same ordering. The range is fromIndex inclusive to toIndex
28 * exclusive; absence returns -(insertionIndex + 1).
29 */
30public fun <T : Compare<T>> List<T>.binarySearch(
31 element: T, fromIndex: Long = 0L, toIndex: Long = this.size
32): Long = binarySearch<T>(element, naturalOrder<T>(), fromIndex, toIndex)