Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
127: sort.Search for Binary Search
I've seen a lot of developers dive into the sort package thinking that sort.Search is a direct replacement for a "find" method. They expect it to behave like a standard library function in other languages: you give it a sorted list and a target value, and it either returns the index of that value or a -1 if it's not there. If you try to use it that way, you're going to run into some very frustrating bugs.
The Myth: sort.Search is a "Find Value" Function
Let's look at why that mindset fails. Imagine you have a sorted slice of user IDs and you're looking for ID 42. You might be tempted to write something like this:
ids := []int{10, 20, 30, 40, 50, 60}
target := 42
index := sort.Search(len(ids), func(i int) bool {
return ids[i] >= target
})
fmt.Println("Found at:", index)
// You're expecting -1, but you'll actually get 4.
Wait, index 4? That's the value 50. The code didn't "fail" to find 42; it did exactly what it was told. The problem is that sort.Search doesn't actually search for a value—it searches for a boundary.
The Reality: Finding the First True
The real job of sort.Search is to find the smallest index i in the range [0, n) where your provided function returns true. It assumes that your function is "monotonic"—meaning once it starts returning true, it stays true for every index after that. It's essentially finding the point where the result flips from false to true.
In the example above, the function ids[i] >= 42 returns false for indices 0, 1, 2, and 3. At index 4 (value 50), it becomes true. Since 4 is the first index where the condition is met, that's what it returns. It has no internal concept of "equality" or "missing values."
To actually use this for a binary search where you need to know if the element exists, you have to perform a manual check after the search finishes. I always follow this pattern:
ids := []int{10, 20, 30, 40, 50, 60}
target := 42
i := sort.Search(len(ids), func(i int) bool {
return ids[i] >= target
})
// 1. Check if the index is within bounds
// 2. Check if the value at that index is actually our target
if i < len(ids) && ids[i] == target {
fmt.Printf("Found %d at index %d\n", target, i)
} else {
fmt.Printf("%d not found in slice\n", target)
}
This adds a tiny bit of boilerplate, but it's the only way to be safe. The beauty of this design is its flexibility. Because you provide the function, you aren't limited to searching for exact matches. You can find the first element that exceeds a certain value, the first string that starts with a specific prefix, or the first timestamp that falls within a certain window—as long as the data is sorted in a way that makes the false-to-true transition happen exactly once.
📋 Practical Task
Implementing a "First Version with Bug" Finder
In software release management, we often use binary search to find the first "bad" commit in a sorted sequence of versions. Given a sorted slice of version numbers (integers), write a function FindFirstBuggyVersion that uses sort.Search to identify the first version that is buggy.
You are provided with a helper function isBuggy(version int) bool. This function mimics an external test suite that returns true if a version is buggy and false otherwise. Assume that once a bug is introduced, all subsequent versions are also buggy.
Requirements:
- The function should take a slice of sorted version numbers
[]int. - Use
sort.Searchto find the index of the first buggy version. - If no buggy version is found in the slice, return
-1. - Otherwise, return the actual version number (the value from the slice).
// Provided helper (do not modify)
func isBuggy(version int) bool {
// Imagine version 104 was the first commit that broke the build
return version >= 104
}
func FindFirstBuggyVersion(versions []int) int {
// Your code here
}
There are no comments for now.