Skip to content

Commit c51b10a

Browse files
authored
Merge pull request #34814 from lorentey/partitioning-cleanup
[stdlib][NFC] Simplify partition(by:)’s implementation
2 parents b0be562 + cb8ceed commit c51b10a

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

stdlib/public/core/CollectionAlgorithms.swift

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -401,35 +401,30 @@ extension MutableCollection where Self: BidirectionalCollection {
401401
) rethrows -> Index {
402402
var lo = startIndex
403403
var hi = endIndex
404+
while true {
405+
// Invariants at this point:
406+
//
407+
// * `lo <= hi`
408+
// * all elements in `startIndex ..< lo` belong in the first partition
409+
// * all elements in `hi ..< endIndex` belong in the second partition
404410

405-
// 'Loop' invariants (at start of Loop, all are true):
406-
// * lo < hi
407-
// * predicate(self[i]) == false, for i in startIndex ..< lo
408-
// * predicate(self[i]) == true, for i in hi ..< endIndex
409-
410-
Loop: while true {
411-
FindLo: repeat {
412-
while lo < hi {
413-
if try belongsInSecondPartition(self[lo]) { break FindLo }
414-
formIndex(after: &lo)
415-
}
416-
break Loop
417-
} while false
411+
// Find next element from `lo` that may not be in the right place.
412+
while true {
413+
guard lo < hi else { return lo }
414+
if try belongsInSecondPartition(self[lo]) { break }
415+
formIndex(after: &lo)
416+
}
418417

419-
FindHi: repeat {
418+
// Find next element down from `hi` that we can swap `lo` with.
419+
while true {
420420
formIndex(before: &hi)
421-
while lo < hi {
422-
if try !belongsInSecondPartition(self[hi]) { break FindHi }
423-
formIndex(before: &hi)
424-
}
425-
break Loop
426-
} while false
421+
guard lo < hi else { return lo }
422+
if try !belongsInSecondPartition(self[hi]) { break }
423+
}
427424

428425
swapAt(lo, hi)
429426
formIndex(after: &lo)
430427
}
431-
432-
return lo
433428
}
434429
}
435430

0 commit comments

Comments
 (0)