0
0
DSA Goprogramming~30 mins

Binary Search Iterative Approach in DSA Go - Build from Scratch

Choose your learning style9 modes available
Binary Search Iterative Approach
📖 Scenario: You have a sorted list of book IDs in a library system. You want to quickly find if a specific book ID is available using a fast search method.
🎯 Goal: Build a program that uses the iterative binary search method to find a book ID in a sorted list.
📋 What You'll Learn
Create a sorted slice of integers called bookIDs with the exact values: 101, 203, 305, 407, 509, 611, 713
Create an integer variable called target with the value 407
Implement an iterative binary search function called binarySearch that takes bookIDs and target as parameters and returns the index of target or -1 if not found
Print the result index returned by binarySearch
💡 Why This Matters
🌍 Real World
Binary search is used in many real-world applications like searching in databases, looking up words in dictionaries, or finding items in sorted lists quickly.
💼 Career
Understanding binary search is essential for software developers and engineers to write efficient search algorithms and optimize performance in applications.
Progress0 / 4 steps
1
Create the sorted list of book IDs
Create a slice of integers called bookIDs with these exact values: 101, 203, 305, 407, 509, 611, 713
DSA Go
Hint

Use bookIDs := []int{101, 203, 305, 407, 509, 611, 713} to create the slice.

2
Set the target book ID to search
Create an integer variable called target and set it to 407
DSA Go
Hint

Use target := 407 to create the variable.

3
Implement the iterative binary search function
Write a function called binarySearch that takes a slice of integers called arr and an integer target. Use a for loop with variables left and right to search for target iteratively. Return the index if found, otherwise return -1.
DSA Go
Hint

Use a for loop with left and right pointers. Calculate mid as left + (right-left)/2. Compare arr[mid] with target and adjust left or right accordingly.

4
Print the index found by binary search
Call binarySearch with bookIDs and target and print the returned index using fmt.Println
DSA Go
Hint

Use index := binarySearch(bookIDs, target) and then fmt.Println(index) to print the result.