Fixed heapqueue.del for last elem (#5363)

This commit is contained in:
Yuriy Glukhov 2017-02-10 11:15:43 +02:00 • committed by Andreas Rumpf
commit 69fb2c6152

View file

@ -77,7 +77,9 @@ proc pop*[T](heap: var HeapQueue[T]): T =
proc del*[T](heap: var HeapQueue[T], index: int) = proc del*[T](heap: var HeapQueue[T], index: int) =
## Removes element at `index`, maintaining the heap invariant. ## Removes element at `index`, maintaining the heap invariant.
swap(seq[T](heap)[^1], seq[T](heap)[index]) swap(seq[T](heap)[^1], seq[T](heap)[index])
seq[T](heap).setLen(heap.len - 1) let newLen = heap.len - 1
seq[T](heap).setLen(newLen)
if index < newLen:
heap.siftup(index) heap.siftup(index)
proc replace*[T](heap: var HeapQueue[T], item: T): T = proc replace*[T](heap: var HeapQueue[T], item: T): T =
@ -101,16 +103,19 @@ proc pushpop*[T](heap: var HeapQueue[T], item: T): T =
return item return item
when isMainModule: when isMainModule:
proc toSortedSeq[T](h: HeapQueue[T]): seq[T] =
var tmp = h
result = @[]
while tmp.len > 0:
result.add(pop(tmp))
block: # Simple sanity test block: # Simple sanity test
var heap = newHeapQueue[int]() var heap = newHeapQueue[int]()
let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
for item in data: for item in data:
push(heap, item) push(heap, item)
doAssert(heap[0] == 0) doAssert(heap[0] == 0)
var sort = newSeq[int]() doAssert(heap.toSortedSeq == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
while heap.len > 0:
sort.add(pop(heap))
doAssert(sort == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
block: # Test del block: # Test del
var heap = newHeapQueue[int]() var heap = newHeapQueue[int]()
@ -121,11 +126,27 @@ when isMainModule:
doAssert(heap[0] == 1) doAssert(heap[0] == 1)
heap.del(seq[int](heap).find(7)) heap.del(seq[int](heap).find(7))
heap.del(seq[int](heap).find(5)) doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 5, 6, 8, 9])
heap.del(seq[int](heap).find(6))
heap.del(seq[int](heap).find(2))
var sort = newSeq[int]() heap.del(seq[int](heap).find(5))
while heap.len > 0: doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 6, 8, 9])
sort.add(pop(heap))
doAssert(sort == @[1, 3, 4, 8, 9]) heap.del(seq[int](heap).find(6))
doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 8, 9])
heap.del(seq[int](heap).find(2))
doAssert(heap.toSortedSeq == @[1, 3, 4, 8, 9])
block: # Test del last
var heap = newHeapQueue[int]()
let data = [1, 2, 3]
for item in data: push(heap, item)
heap.del(2)
doAssert(heap.toSortedSeq == @[1, 2])
heap.del(1)
doAssert(heap.toSortedSeq == @[1])
heap.del(0)
doAssert(heap.toSortedSeq == @[])