Implement binarySearch method for UArrays (KT-27262)

This commit is contained in:
Abduqodiri Qurbonzoda
2019-01-23 18:47:36 +03:00
committed by Ilya Gorbunov
parent 6cd9858147
commit 550c74bb6b
4 changed files with 292 additions and 1 deletions
@@ -2287,6 +2287,14 @@ public abstract class kotlin/collections/ShortIterator : java/util/Iterator, kot
}
public final class kotlin/collections/UArraysKt {
public static final fun binarySearch-2fe2U9s ([IIII)I
public static synthetic fun binarySearch-2fe2U9s$default ([IIIIILjava/lang/Object;)I
public static final fun binarySearch-EtDCXyQ ([SSII)I
public static synthetic fun binarySearch-EtDCXyQ$default ([SSIIILjava/lang/Object;)I
public static final fun binarySearch-K6DWlUc ([JJII)I
public static synthetic fun binarySearch-K6DWlUc$default ([JJIIILjava/lang/Object;)I
public static final fun binarySearch-WpHrYlw ([BBII)I
public static synthetic fun binarySearch-WpHrYlw$default ([BBIIILjava/lang/Object;)I
public static final fun contentEquals-ctEhBpI ([I[I)Z
public static final fun contentEquals-kdPth3s ([B[B)Z
public static final fun contentEquals-mazbYpA ([S[S)Z
@@ -1218,7 +1218,7 @@ object ArrayOps : TemplateGroupBase() {
val f_binarySearch = fn("binarySearch(element: T, fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(ArraysOfObjects, ArraysOfPrimitives)
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
exclude(PrimitiveType.Boolean)
} builder {
doc {
@@ -1238,6 +1238,55 @@ object ArrayOps : TemplateGroupBase() {
body {
"return java.util.Arrays.binarySearch(this, fromIndex, toIndex, element)"
}
specialFor(ArraysOfUnsigned) {
val elementConversion: String
val midValConversion: String
val compareFunction: String
when (primitive!!) {
PrimitiveType.UByte, PrimitiveType.UShort -> {
elementConversion = ".toInt()"
midValConversion = ".toInt()"
compareFunction = "uintCompare"
}
PrimitiveType.UInt -> {
elementConversion = ".toInt()"
midValConversion = ""
compareFunction = "uintCompare"
}
PrimitiveType.ULong -> {
elementConversion = ".toLong()"
midValConversion = ""
compareFunction = "ulongCompare"
}
else -> error(primitive!!)
}
body {
"""
AbstractList.checkRangeIndexes(fromIndex, toIndex, size)
val signedElement = element$elementConversion
var low = fromIndex
var high = toIndex - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = storage[mid]
val cmp = $compareFunction(midVal$midValConversion, signedElement)
if (cmp < 0)
low = mid + 1
else if (cmp > 0)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
"""
}
}
}
val f_binarySearch_comparator = fn("binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size)") {