scoop:scoop.std:0.1.0
src/collections/binary_search.scoop
Selected production source · src/collections/binary_search.scoop
1
package scoop.collections3
import scoop.comparisons.Comparator4
import scoop.comparisons.naturalOrder6
/**7
* Searches a range sorted by the same ordering. The range is fromIndex inclusive to toIndex8
* exclusive; absence returns -(insertionIndex + 1).9
*/10
public fun <T> List<T>.binarySearch(11
element: T, comparator: Comparator<T>, fromIndex: Long = 0L, toIndex: Long = this.size12
): 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 = fromIndex16
var high = toIndex17
while (low < high) {18
val middle = low + (high - low) / 2L19
val compared = comparator.compare(this[middle], element)20
if (compared == 0L) return middle21
if (compared < 0L) low = middle + 1L else high = middle22
}23
return -low - 1L24
}26
/**27
* Searches a range sorted by the same ordering. The range is fromIndex inclusive to toIndex28
* exclusive; absence returns -(insertionIndex + 1).29
*/30
public fun <T : Compare<T>> List<T>.binarySearch(31
element: T, fromIndex: Long = 0L, toIndex: Long = this.size32
): Long = binarySearch<T>(element, naturalOrder<T>(), fromIndex, toIndex)