Implement the binary search algorithm to efficiently find items in a sorted collection. Binary search is a divide-and-conquer algorithm that repeatedly divides the search space in half, making it much faster than linear search for sorted data.
You'll implement three versions of binary search:
BinarySearch- Standard binary search that returns the index of a target value.BinarySearchRecursive- A recursive implementation of binary search.FindInsertPosition- Find the position where a value should be inserted to maintain sorted order.
func BinarySearch(arr []int, target int) int
func BinarySearchRecursive(arr []int, target int, left int, right int) int
func FindInsertPosition(arr []int, target int) int- For all functions, a sorted slice of integers
arrand a target integer value. - For the recursive function, additional
leftandrightparameters indicating the search range.
BinarySearchandBinarySearchRecursiveshould return the index of the target if found, or -1 if not found.FindInsertPositionshould return the index where the target should be inserted to maintain sorted order.
- All functions must implement the binary search algorithm, which has O(log n) time complexity.
- The arrays can be assumed to be sorted in ascending order.
BinarySearchRecursivemust use recursion to solve the problem.- If multiple occurrences of the target exist, return the index of any occurrence.
BinarySearch([]int{1, 3, 5, 7, 9}, 5)
2
BinarySearch([]int{1, 3, 5, 7, 9}, 6)
-1
BinarySearchRecursive([]int{1, 3, 5, 7, 9}, 7, 0, 4)
3
FindInsertPosition([]int{1, 3, 5, 7, 9}, 6)
3
- Fork the repository.
- Clone your fork to your local machine.
- Create a directory named after your GitHub username inside
challenge-21/submissions/. - Copy the
solution-template.gofile into your submission directory. - Implement the required functions.
- Test your solution locally by running the test file.
- Commit and push your code to your fork.
- Create a pull request to submit your solution.
Run the following command in the challenge-21/ directory:
go test -v