Merge pull request #2682 from koalazen/refactor_lowerbound_algorithm
shorten lowerBound in algorithm.nim
This commit is contained in:
commit
cb1f1cfd52
1 changed files with 17 additions and 7 deletions
|
|
@ -99,16 +99,13 @@ proc lowerBound*[T](a: openArray[T], key: T, cmp: proc(x,y: T): int {.closure.})
|
||||||
## arr.insert(4, arr.lowerBound(4))
|
## arr.insert(4, arr.lowerBound(4))
|
||||||
## `after running the above arr is `[1,2,3,4,5,6,7,8,9]`
|
## `after running the above arr is `[1,2,3,4,5,6,7,8,9]`
|
||||||
result = a.low
|
result = a.low
|
||||||
var pos = result
|
var count = a.high - a.low + 1
|
||||||
var count, step: int
|
var step, pos: int
|
||||||
count = a.high - a.low + 1
|
|
||||||
while count != 0:
|
while count != 0:
|
||||||
pos = result
|
|
||||||
step = count div 2
|
step = count div 2
|
||||||
pos += step
|
pos = result + step
|
||||||
if cmp(a[pos], key) < 0:
|
if cmp(a[pos], key) < 0:
|
||||||
pos.inc
|
result = pos + 1
|
||||||
result = pos
|
|
||||||
count -= step + 1
|
count -= step + 1
|
||||||
else:
|
else:
|
||||||
count = step
|
count = step
|
||||||
|
|
@ -331,3 +328,16 @@ proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} =
|
||||||
swap x[i-1], x[j]
|
swap x[i-1], x[j]
|
||||||
|
|
||||||
result = true
|
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
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue