# Bug in Heap siftDown implementation?

**URL:** <https://forums.kodeco.com/t/bug-in-heap-siftdown-implementation/171411>\
**Category:** Data Structures & Algorithms in Swift\
**Created:** [May 19, 2022, 1:22am UTC](https://forums.kodeco.com/t/bug-in-heap-siftdown-implementation/171411 "2022-05-19T01:22:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ebelinski](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/ebelinski/32/107969_2.png) [@ebelinski](https://forums.kodeco.com/u/ebelinski)\
**Post date:** [May 19, 2022, 1:22am UTC](https://forums.kodeco.com/t/bug-in-heap-siftdown-implementation/171411/1 "2022-05-19T01:22:48Z")

</div>

I’m looking at the [Heap chapter’s](https://www.raywenderlich.com/books/data-structures-algorithms-in-swift/v4.0/chapters/22-heaps) implementation for `siftDown`:

```auto
mutating func siftDown(from index: Int) {
  var parent = index // 1
  while true { // 2
    let left = leftChildIndex(ofParentAt: parent) // 3
    let right = rightChildIndex(ofParentAt: parent)
    var candidate = parent // 4
    if left < count && sort(elements[left], elements[candidate]) {
      candidate = left // 5
    }
    if right < count && sort(elements[right], elements[candidate]) {
      candidate = right // 6
    }
    if candidate == parent {
      return // 7
    }
    elements.swapAt(parent, candidate) // 8
    parent = candidate
  }
}

```

The explanations for step 5 and 6 are:

1. If there is a left child, and it has a higher priority than its parent, make it the candidate.
2. If there is a right child, and it has an even greater priority, it will become the candidate instead.

However, if we only want to select the right child if it has an “even greater priority”, shouldn’t the comparison be `sort(elements[right], elements[left])`, and not `sort(elements[right], elements[candidate])`?

---

<div class="post-metadata">

**Author:** ![robertomachorro](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/robertomachorro/32/111603_2.png) [@robertomachorro](https://forums.kodeco.com/u/robertomachorro)\
**Post date:** [May 19, 2022, 2:30pm UTC](https://forums.kodeco.com/t/bug-in-heap-siftdown-implementation/171411/2 "2022-05-19T14:30:01Z")

</div>

@jomoka @kelvin_lau any comments?
