diff options
author | Koala Zen <koala@zen.net> | 2015-05-08 09:55:57 -0700 |
---|---|---|
committer | Koala Zen <koala@zen.net> | 2015-05-18 14:59:05 -0700 |
commit | 7a2dce80126dd9397eed8c4461e1aefa33cb3185 (patch) | |
tree | beff13571cb039a3bfcd54ea669386694be73e47 /lib/pure | |
parent | 0b184f2584221543a7dec9c8ae4a700533919e0c (diff) | |
download | Nim-7a2dce80126dd9397eed8c4461e1aefa33cb3185.tar.gz |
refactored lowerBound in algorithm.nim
Diffstat (limited to 'lib/pure')
-rw-r--r-- | lib/pure/algorithm.nim | 24 |
1 files changed, 17 insertions, 7 deletions
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index f7ccb9234..e363b6443 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -88,16 +88,13 @@ proc lowerBound*[T](a: openArray[T], key: T, cmp: proc(x,y: T): int {.closure.}) ## arr.insert(4, arr.lowerBound(4)) ## `after running the above arr is `[1,2,3,4,5,6,7,8,9]` result = a.low - var pos = result - var count, step: int - count = a.high - a.low + 1 + var count = a.high - a.low + 1 + var step, pos: int while count != 0: - pos = result step = count div 2 - pos += step + pos = result + step if cmp(a[pos], key) < 0: - pos.inc - result = pos + result = pos + 1 count -= step + 1 else: count = step @@ -322,3 +319,16 @@ proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} = swap x[i-1], x[j] result = true + +when isMainModule: + # Tests for lowerBound + var arr = @[1,2,3,5,6,7,8,9] + assert arr.lowerBound(0) == 0 + assert arr.lowerBound(4) == 3 + assert arr.lowerBound(5) == 3 + assert arr.lowerBound(10) == 8 + arr = @[1,5,10] + assert arr.lowerBound(4) == 1 + assert arr.lowerBound(5) == 1 + assert arr.lowerBound(6) == 2 + |