         guard var match = anyIndex(of: element) else { return nil }
         // Walk backward to find the first matching element (in case there are duplicates)
         while let predecessor = index(match, offsetBy: -1, limitedBy: startIndex) {
-            if compare(lhs: self[predecessor], rhs: element) == .orderedSame {
+            if compare(self[predecessor], element) == .orderedSame {
                 match = predecessor
             } else {
                 break

        // Walk forward to find the last matching element (in case there are duplicates)
        let lastValidIndex = index(before: endIndex)
        while let successor = index(match, offsetBy: 1, limitedBy: lastValidIndex) {
            if compare(lhs: self[successor], rhs: element) == .orderedSame {
                match = successor
            } else {
                break


// MARK: - Converting between a stdlib comparator function and Foundation.ComparisonResult
extension SortedArray {
    fileprivate func compare(_ lhs: Element, _ rhs: Element) -> Foundation.ComparisonResult {
        if areInIncreasingOrder(lhs, rhs) {
            return .orderedAscending
        } else if areInIncreasingOrder(rhs, lhs) {
