# WWDC 2018 Swift Generic: binary search algorithm: BidirectionalCollection vs. RandomAccessCollection

**URL:** <https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078>\
**Category:** Using Swift\
**Created:** [February 25, 2021, 4:03am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078 "2021-02-25T04:03:13Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [February 25, 2021, 4:03am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/1 "2021-02-25T04:03:13Z")

</div>

In [WWDC 2018 Swift Generics](https://developer.apple.com/videos/play/wwdc2018/406/) (the online video doesn't play for me, must download the mp4). At 21:07, the binary search insertion example @Douglas_Gregor uses `RandomAccessCollection`, but `BidirectionalCollection` also works and is more general. Is there some reason for this? For my own binary search I use `BidirectionalCollection`, want to be sure I'm not making a mistake and should use `RandomAccessCollection` instead.

```swift
// BidirectionalCollection is more general and works just as well
// is there good reason this example used RandomAccessCollection?
// vvvvvvvvvvvvvvvvvvvvvv
extension BidirectionalCollection/*RandomAccessCollection*/ where Element: Comparable {
    func sortedInsertionPointRecursive(of value: Element) -> Index {
        if isEmpty { return startIndex }
        let middle = index(startIndex, offsetBy: count / 2)
        if value < self[middle] {
            return self[..<middle].sortedInsertionPoint(of: value)
        } else {
            return self[index(after: middle)...].sortedInsertionPoint(of: value)
        }
    }

    // non-recursive version
    func sortedInsertionPoint(of value: Element) -> Index {
        // cannot do type inference: error: Expected type
        var slice: SubSequence = self[...]

        while !slice.isEmpty {
            let middle = slice.index(slice.startIndex, offsetBy: slice.count / 2)
            if value < slice[middle] {
                slice = slice[..<middle]
            } else {
                slice = slice[index(after: middle)...]
            }
        }

        return slice.startIndex
    }
}

```

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [February 25, 2021, 4:09am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/2 "2021-02-25T04:09:48Z")

</div>

> [@young](#):
>
> `index(startIndex, offsetBy: count / 2)`

The key is right here. To ensure that binary search performs on logarithmic time, you need be able to jump to the middle entry in `O(1)`. That performance is guaranteed by `RandomAccessCollection`, but not `BidirectionalCollection`.

* * *

Now, if you use `BidirectionalCollection`, it can only guarantee up to `O(k)`. If you do the math, the entire binary search will take `O(n)` time. Not terrible, but you might as well just look at each element one by one.

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [February 25, 2021, 4:28am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/3 "2021-02-25T04:28:29Z")

</div>

I thought even though the extension is on `BidirectionalCollection`, if you call it on a `RandomAccessCollection`, then it will call the `index(:offsetBy:)` on that, which is O(1).

And on a `BidirectionalCollection`, it O(0).

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [February 25, 2021, 4:35am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/4 "2021-02-25T04:35:46Z")

</div>

> [@young](#):
>
> if you call it on a `RandomAccessCollection` , then it will call the `index(:offsetBy:)` on that, which is O(1).

That is correct. Still, it doesn't change the fact that this isn't a great tool for a general `BidirectionalCollection` to have. I mean, I won't stop you, but as said, a simple for-loop will probably work just as well.

> [@young](#):
>
> And on a `BidirectionalCollection` , it O(0).

It's not `O(0)`, not guaranteed to be, anyway.

You can try to think about how it'd work with `String`, which has non-uniform element size (and is bidi).

* * *

Also, treaded carefully, even `Collection` would provide the _correct_ result.

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [February 25, 2021, 5:02am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/5 "2021-02-25T05:02:32Z")

</div>

I view these functions as algorithm operating on any collection, its performance characteristic is determined by the implementation of the actual Collection and it's up to the caller to decide.

> [@Lantua](#):
>
> even `Collection` would provide the _correct_ result

I just noticed this also. He uses `SubSequence` and doesn't use `index(before:)`, seem even better to be able to used on any `Collection`.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [February 25, 2021, 8:29am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/6 "2021-02-25T08:29:14Z")

</div>

I have my quarrels with the whole `Sequence`-hierarchy, but imho (this applies to the whole of this post ;-) `BidirectionalCollection` is especially odd: I couldn't tell a single conforming type that is not also `RandomAccessCollection` — and the name shouts "DoubleLinkedList" at me (which is a very basic and prominent concept, but does not fit well into the system of protocols at all).  
So the benefit of `BidirectionalCollection` is just theory, whereas in practice it might bite you because of some default implementation (but that's less than a theory, and I didn't check if offset operations are slower when you use a `RandomAccessCollection` as `BidirectionalCollection`).

Therefor, I'd ignore `BidirectionalCollection` as well.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [February 25, 2021, 5:36pm UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/7 "2021-02-25T17:36:09Z")

</div>

> [@Tino](#):
>
> I couldn't tell a single conforming type that is not also `RandomAccessCollection`

`String`

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [February 25, 2021, 7:34pm UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/8 "2021-02-25T19:34:50Z")

</div>

🙂 of course — `String`! But is that actually the only one?  
However, with all its unicode-quirks, `String` is somewhat special anyways — and afaics, `index(before:)` should be quite complex as well.  
Surprisingly, `Slice` is also marked bidirectional, even when the base collection isn't… so `BidirectionalCollection` really does not seem to offer strong guarantees.

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [February 25, 2021, 7:50pm UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/9 "2021-02-25T19:50:31Z")

</div>

> [@Tino](#):
>
> Surprisingly, `Slice` is also marked bidirectional, even when the base collection isn't

Hmm? Why do you think that?

> <https://github.com/apple/swift/blob/9bf4fe8db429263a353ed2f3f4ddbfa6cc4018c2/stdlib/public/core/Slice.swift#L232>

* * *

There's also `IndexSet`, but what you want right now probably isn't another example.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [February 26, 2021, 9:23am UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/10 "2021-02-26T09:23:20Z")

</div>

Makes sense — but does [Apple Developer Documentation](https://developer.apple.com/documentation/swift/slice) reflect the code? Afaics, it doesn't mention that conformance is conditional (#site-feedback ? ;-)

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [February 26, 2021, 12:27pm UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/11 "2021-02-26T12:27:29Z")

</div>

No idea where to report. Maybe Apple's feedback assistant ([https://feedbackassistant.apple.com/](https://feedbackassistant.apple.com/)) as well?

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [February 26, 2021, 5:26pm UTC](https://forums.swift.org/t/wwdc-2018-swift-generic-binary-search-algorithm-bidirectionalcollection-vs-randomaccesscollection/45078/12 "2021-02-26T17:26:52Z")

</div>

Isn't this documented in section "[Slices Inherit Semantics](https://developer.apple.com/documentation/swift/slice)"?
