Skip to Content
Course content

127: sort.Search for Binary Search

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.Search to 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
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.