Binary search is a powerful and efficient searching technique, crucial for any programmer. In this guide, we’ll walk through implementing a binary search in Golang, emphasizing the fundamental rules of binary searching.
What’s Inside
Key Rules for Binary Searching
- Sorted Input Array: The array you’re searching through must be sorted in ascending order for binary search to work effectively.
- Find the Mid-Index: Calculate the mid-index of the array to identify the middle element.
- Comparisons: Based on the comparison of the middle element with the target value, decide whether to search the left or right portion of the array.
- If the middle element is greater than the target, search in the left portion (update the end index).
- If the middle element is less than the target, search in the right portion (update the start index).
Golang Code for Binary Search
package main import ( "fmt" ) func main() { // Sorted array for binary search a := []int{6, 8, 31, 54, 67, 71, 84, 95} // Display the original array fmt.Printf("Original Array: %v\n", a) // User input for the element to be searched fmt.Println("Please enter the search value:") var searchElem int fmt.Scanf("%d", &searchElem) fmt.Printf("Searching for %d...\n", searchElem) // Initialize variables for binary search start, end := 0, len(a)-1 var mid int // Binary search loop for start <= end { mid = (start + end) / 2 if searchElem == a[mid] { fmt.Printf("%d found at location %d.\n", searchElem, mid+1) break } else if searchElem > a[mid] { start = mid + 1 } else if searchElem < a[mid] { end = mid - 1 } } // Display the result if the element is not found if start > end { fmt.Printf("Not found! %d isn't present in the list.\n", searchElem) } }
By following this practical guide, you’ve gained insights into the key principles and a hands-on experience in coding a binary search algorithm in Golang. Happy coding!
You May Also Like: