B-Tree Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓B-Tree runs in O(log n) time and O(n) space, in Swift as in every other language.
- ✓Nothing ordered, and unusually the standard library does not even ship a binary search: Array has firstIndex(where:) which is a linear scan.
- ✓Write a partitioningIndex(where:) helper over a sorted Array, which is the shape Apple standardised in the swift-collections package, and use it as the lower bound for both lookup and insertion.
- ✓The Swift trap: Dictionary iteration order is not merely unspecified, it is deliberately randomised by a per-process hash seed, so two runs of the same program produce different orders and a test that passes locally can fail in CI.
- ✓Array is contiguous with copy-on-write, so a sorted array is cache-resident and outperforms a node tree well past ten thousand elements.
What B-Tree actually is
B-Tree in Swift: what you actually reach for
Swift implementation
extension Array {
/// Lower bound: the first index whose element does NOT satisfy the
/// predicate. The standard library ships no binary search at all, so
/// this is the helper every ordered-array design needs first.
func partitioningIndex(where belongsBefore: (Element) -> Bool) -> Int {
var lo = startIndex
var hi = endIndex
while lo < hi {
let mid = lo + (hi - lo) / 2
if belongsBefore(self[mid]) { lo = mid + 1 } else { hi = mid }
}
return lo
}
}
struct SortedIndex<Key: Comparable> {
private(set) var keys: [Key] = []
mutating func insert(_ key: Key) -> Bool {
let i = keys.partitioningIndex { $0 < key }
if i < keys.count && keys[i] == key { return false }
keys.insert(key, at: i) // O(n) shift
return true
}
func contains(_ key: Key) -> Bool {
let i = keys.partitioningIndex { $0 < key }
return i < keys.count && keys[i] == key
}
func range(_ lo: Key, _ hi: Key) -> ArraySlice<Key> {
let start = keys.partitioningIndex { $0 < lo }
let end = keys.partitioningIndex { $0 <= hi }
return keys[start..<end]
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for B-Tree?
Nothing ordered, and unusually the standard library does not even ship a binary search: Array has firstIndex(where:) which is a linear scan. Dictionary is a hash whose iteration order is randomised per process by a seed.
What is the most common Swift mistake when implementing B-Tree?
Dictionary iteration order is not merely unspecified, it is deliberately randomised by a per-process hash seed, so two runs of the same program produce different orders and a test that passes locally can fail in CI. Reaching for sorted() on every access to compensate turns an O(1) lookup into an O(n log n) one. The absence of a stdlib binary search is the second half of the problem: people write firstIndex(where:) on a sorted array, get correct answers, and never notice it is linear.
How does B-Tree actually perform in Swift?
Array is contiguous with copy-on-write, so a sorted array is cache-resident and outperforms a node tree well past ten thousand elements. Reserve capacity up front, because the geometric growth copies dominate a build loop. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.