Skip to content

[stdlib][QoI] Replace recursion in sort _siftDown with Iteration #18629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 26 additions & 27 deletions stdlib/public/core/Sort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -516,35 +516,34 @@ internal func _siftDown<C: MutableCollection & RandomAccessCollection>(
subRange range: Range<C.Index>,
by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool
) rethrows {

let countToIndex = elements.distance(from: range.lowerBound, to: index)
let countFromIndex = elements.distance(from: index, to: range.upperBound)
// Check if left child is within bounds. If not, return, because there are
var i = index
var countToIndex = elements.distance(from: range.lowerBound, to: i)
var countFromIndex = elements.distance(from: i, to: range.upperBound)
// Check if left child is within bounds. If not, stop iterating, because there are
// no children of the given node in the heap.
if countToIndex + 1 >= countFromIndex {
return
}
let left = elements.index(index, offsetBy: countToIndex + 1)
var largest = index
if (try areInIncreasingOrder(elements[largest], elements[left])) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = elements.index(after: left)
if (try areInIncreasingOrder(elements[largest], elements[right])) {
largest = right
while countToIndex + 1 < countFromIndex {
let left = elements.index(i, offsetBy: countToIndex + 1)
var largest = i
if try areInIncreasingOrder(elements[largest], elements[left]) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = elements.index(after: left)
if try areInIncreasingOrder(elements[largest], elements[right]) {
largest = right
}
}
// If a child is bigger than the current node, swap them and continue sifting
// down.
if largest != i {
elements.swapAt(index, largest)
i = largest
countToIndex = elements.distance(from: range.lowerBound, to: i)
countFromIndex = elements.distance(from: i, to: range.upperBound)
} else {
break
}
}
// If a child is bigger than the current node, swap them and continue sifting
// down.
if largest != index {
elements.swapAt(index, largest)
try _siftDown(
&elements,
index: largest,
subRange: range
, by: areInIncreasingOrder)
}
}

Expand Down