B-Tree Implementation in Go
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 Go as in every other language.
- ✓No ordered map and no tree. The built-in map is a hash table, and sort.Search provides binary search over anything you can index.
- ✓Keep a sorted slice and use sort.Search for read-mostly data, or take the btree dependency for write-heavy ordered workloads.
- ✓The Go trap: Go deliberately randomises map iteration order on every run, so a map can never stand in for an ordered structure, and code that appears to iterate in a stable order during development will produce different output in production.
- ✓A sorted slice of int is one contiguous allocation, so binary search is cache-friendly and the compiler removes most bounds checks.
What B-Tree actually is
B-Tree in Go: what you actually reach for
Go implementation
package index
import "slices"
// Ordered integer index over a sorted slice.
// Since Go 1.21, slices.BinarySearch is the idiomatic form.
type SortedIndex struct {
keys []int
}
func (s *SortedIndex) Add(k int) bool {
i, found := slices.BinarySearch(s.keys, k)
if found {
return false
}
s.keys = slices.Insert(s.keys, i, k) // O(n) shift, one memmove
return true
}
func (s *SortedIndex) Has(k int) bool {
_, found := slices.BinarySearch(s.keys, k)
return found
}
// Range returns keys in [lo, hi]. A map could never answer this.
func (s *SortedIndex) Range(lo, hi int) []int {
start, _ := slices.BinarySearch(s.keys, lo)
end, _ := slices.BinarySearch(s.keys, hi+1)
return s.keys[start:end]
}
// Why a map is not an option here: Go randomises map iteration order
// on purpose, per run, so this would print a different order each time.
func DeterministicKeys(m map[int]string) []int {
keys := make([]int, 0, len(m))
for k := range m {
keys = append(keys, k)
}
slices.Sort(keys) // the sort is REQUIRED, not a nicety
return keys
}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 Go-specific trap
Performance in Go, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for B-Tree?
No ordered map and no tree. The built-in map is a hash table, and sort.Search provides binary search over anything you can index. Google publishes github.com/google/btree, which is the de-facto answer when a real B-tree is needed.
What is the most common Go mistake when implementing B-Tree?
Go deliberately randomises map iteration order on every run, so a map can never stand in for an ordered structure, and code that appears to iterate in a stable order during development will produce different output in production. This is a design decision rather than an implementation detail: the runtime picks a random starting bucket precisely so that nobody depends on the order. Any place you need determinism, collect the keys and sort them explicitly.
How does B-Tree actually perform in Go?
A sorted slice of int is one contiguous allocation, so binary search is cache-friendly and the compiler removes most bounds checks. The btree package pays off when insertions are frequent enough that the O(n) shift in a slice dominates. 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 trialMost AI and dev tools have a student plan. See which ones and how to claim them 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.