Skip to content

Commit acb3583

Browse files
authored
Cleaning up iterators logic
1 parent bf31ba1 commit acb3583

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

Sources/Algorithms/PartialSort.swift

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -161,33 +161,36 @@ extension MutableCollection where Self: RandomAccessCollection {
161161
Cannot partially sort with a negative amount of elements!
162162
"""
163163
)
164-
165164
assert(k <= count, """
166165
Cannot partially sort more than this Sequence's size!
167166
"""
168167
)
169168

170-
guard k > 0 else {
171-
return
172-
}
173-
guard isEmpty == false else {
169+
guard isEmpty == false && k > 0 else {
174170
return
175171
}
172+
176173
var heapEndIndex = 0
177174
for i in (count / 2)..<count {
178175
try siftDown(i, by: areInIncreasingOrder, heapEndIndex: heapEndIndex)
179176
}
180-
var iterator = (0..<k).makeIterator()
181-
_ = iterator.next()
182-
swapAt(index(before: endIndex), index(startIndex, offsetBy: heapEndIndex))
177+
178+
swapAt(
179+
index(before: endIndex),
180+
index(startIndex, offsetBy: heapEndIndex)
181+
)
183182
heapEndIndex += 1
184-
while let _ = iterator.next() {
183+
184+
for i in 1..<k {
185185
try siftDown(
186186
count - 1,
187187
by: areInIncreasingOrder,
188188
heapEndIndex: heapEndIndex
189189
)
190-
swapAt(index(before: endIndex), index(startIndex, offsetBy: heapEndIndex))
190+
swapAt(
191+
index(before: endIndex),
192+
index(startIndex, offsetBy: heapEndIndex)
193+
)
191194
heapEndIndex += 1
192195
}
193196
}

0 commit comments

Comments
 (0)