diff options
author | Arne Döring <arne.doering@gmx.net> | 2018-05-03 17:23:13 +0200 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2018-05-03 17:23:13 +0200 |
commit | f94fafff9b6734a82bd252a03ba19057e1913cb8 (patch) | |
tree | 2a6ca99045574e2a3c702888ecccbe151230c581 /lib | |
parent | 9735bb46be68a9c61d86ea08d594ba800219b574 (diff) | |
download | Nim-f94fafff9b6734a82bd252a03ba19057e1913cb8.tar.gz |
Deprecate smart binary search (#7745)
* deprecate smartBinarySearch * changelog entry
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/algorithm.nim | 34 |
1 files changed, 19 insertions, 15 deletions
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 45e031574..4f7880fec 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -69,21 +69,25 @@ proc reversed*[T](a: openArray[T]): seq[T] = proc binarySearch*[T](a: openArray[T], key: T): int = ## binary search for `key` in `a`. Returns -1 if not found. - var b = len(a) - while result < b: - var mid = (result + b) div 2 - if a[mid] < key: result = mid + 1 - else: b = mid - if result >= len(a) or a[result] != key: result = -1 - -proc smartBinarySearch*[T](a: openArray[T], key: T): int = - ## ``a.len`` must be a power of 2 for this to work. - var step = a.len div 2 - while step > 0: - if a[result or step] <= key: - result = result or step - step = step shr 1 - if a[result] != key: result = -1 + if ((a.len - 1) and a.len) == 0: + # when `a.len` is a power of 2, a faster div can be used. + var step = a.len div 2 + while step > 0: + if a[result or step] <= key: + result = result or step + step = step shr 1 + if a[result] != key: result = -1 + else: + var b = len(a) + while result < b: + var mid = (result + b) div 2 + if a[mid] < key: result = mid + 1 + else: b = mid + if result >= len(a) or a[result] != key: result = -1 + +proc smartBinarySearch*[T](a: openArray[T], key: T): int {.deprecated.} = + ## **Deprecated since version 0.18.1**; Use ``binarySearch`` instead. + binarySearch(a,key) const onlySafeCode = true |