Binary Search : Mastering Efficiency

Binary Search : Mastering Efficiency

Mastering Binary Search in Kotlin: A Beginner-Friendly Guide.

ยท

4 min read

Ever wondered how Google finds your search results so quickly? Or perhaps you've been in a library searching for a book? These everyday situations rely on Binary Search, an elegant and powerful algorithm. Let's explore Binary Search using Kotlin, with real-life examples, in an easy-to-understand way.

Binary Search is a smart detective. It works like this:

  1. Sort the List: Imagine you have a dictionary, and you want to find a word. First, make sure your book is sorted alphabetically.

  2. Divide and Conquer: Binary Search breaks the problem into smaller pieces. It starts by checking the word in the middle of the book.

  3. The "Aha!" Moment: If that word is what you're looking for, you're done! If not, you'll know whether your word is before or after the word in the middle.

  4. Choose a Half: Based on this discovery, you discard half of the book. You're now only interested in the remaining half.

  5. Repeat: Keep doing this until you find your word or you've narrowed it down to just one possibility.

Binary Search in Everyday Life

Let's relate this to everyday situations:

1. Finding a Word in a Dictionary

Imagine you're looking for the word "serendipity" in a giant dictionary. You open it in the middle and see "scoop." Since "serendipity" is further down the alphabet, you know it must be in the latter part of the dictionary. You've already eliminated half of the book. Repeat until you find it.

Ever wonder how Google retrieves search results from billions of web pages almost instantly? Binary Search is the secret. Google organizes web pages by keywords. When you search for "puppies," Google doesn't check every page. It does a Binary Search in its keyword index, quickly narrowing down the relevant pages.

3. Phonebook Efficiency

Before smartphones, phonebooks were our contacts database. Searching for "Romman Sabbir"? You wouldn't start from page one. You'd open somewhere in the middle, say "Roman," and decide whether to look before or after that point. Binary Search is in action again!

Let's Get Coding in Kotlin

fun binarySearch(arr: List<Int>, target: Int): Int? {
    var left = 0
    var right = arr.size - 1

    while (left <= right) {
        val mid = left + (right - left) / 2

        if (arr[mid] == target) {
            return mid // Found the target
        } else if (arr[mid] < target) {
            left = mid + 1 // Adjust left boundary
        } else {
            right = mid - 1 // Adjust right boundary
        }
    }

    return null // Target not found
}

This Kotlin function finds a number in a sorted list (arr). It uses left and right as search boundaries.

How Binary Search Works

  1. Initialize: Start with the entire collection (left at the start and right at the end).

  2. Divide: Calculate the middle element (mid) in the current search space.

  3. Conquer: Compare arr[mid] with the target:

    • If they match, return the target's index.

    • If arr[mid] is less than the target, move left to mid + 1.

    • If arr[mid] is greater than the target, move right to mid - 1.

  4. Repeat: Keep dividing the search space and repeating steps 2 and 3 until the target is found or there's only one possibility left.

Putting It to the Test

Let's find the number 11 in a sorted list of numbers:

fun main() {
    val numbers = listOf(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
    val target = 11

    val result = binarySearch(numbers, target)

    if (result != null) {
        println("Found $target at index $result.")
    } else {
        println("$target not found in the list.")
    }
}

Running this code prints "Found 11 at index 5."

Efficiency and Conclusion

Binary Search's beauty lies in its efficiency. It has a time complexity of O(log n), meaning it can locate an item in a sorted list of n elements in logarithmic time. In contrast, linear search has a time complexity of O(n), making it much slower for larger collections.


That's it for today. Happy Coding...

ย