Skip to content

Commit f0e69c7

Browse files
Add solution for Challenge 21 (#1195)
Co-authored-by: go-interview-practice-bot[bot] <230190823+go-interview-practice-bot[bot]@users.noreply.github.com>
1 parent cc180db commit f0e69c7

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
// Example sorted array for testing
9+
arr := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
10+
11+
// Test binary search
12+
target := 7
13+
index := BinarySearch(arr, target)
14+
fmt.Printf("BinarySearch: %d found at index %d\n", target, index)
15+
16+
// Test recursive binary search
17+
recursiveIndex := BinarySearchRecursive(arr, target, 0, len(arr)-1)
18+
fmt.Printf("BinarySearchRecursive: %d found at index %d\n", target, recursiveIndex)
19+
20+
// Test find insert position
21+
insertTarget := 8
22+
insertPos := FindInsertPosition(arr, insertTarget)
23+
fmt.Printf("FindInsertPosition: %d should be inserted at index %d\n", insertTarget, insertPos)
24+
}
25+
26+
// BinarySearch performs a standard binary search to find the target in the sorted array.
27+
// Returns the index of the target if found, or -1 if not found.
28+
func BinarySearch(arr []int, target int) int {
29+
// TODO: Implement this function
30+
left, right := 0, len(arr) - 1
31+
for left <= right {
32+
mid := left + (right - left) / 2
33+
if arr[mid] == target {
34+
return mid
35+
} else if arr[mid] < target {
36+
left = mid + 1
37+
} else {
38+
right = mid - 1
39+
}
40+
}
41+
return -1
42+
}
43+
44+
// BinarySearchRecursive performs binary search using recursion.
45+
// Returns the index of the target if found, or -1 if not found.
46+
func BinarySearchRecursive(arr []int, target int, left int, right int) int {
47+
// TODO: Implement this function
48+
if left > right {
49+
return -1
50+
}
51+
mid := left + (right - left) / 2
52+
if arr[mid] > target {
53+
return BinarySearchRecursive(arr, target, left, mid - 1)
54+
} else if arr[mid] < target {
55+
return BinarySearchRecursive(arr, target, mid + 1, right)
56+
}
57+
return mid
58+
}
59+
60+
// FindInsertPosition returns the index where the target should be inserted
61+
// to maintain the sorted order of the array.
62+
func FindInsertPosition(arr []int, target int) int {
63+
// TODO: Implement this function
64+
left, right := 0, len(arr)
65+
for left < right {
66+
mid := left + (right - left) / 2
67+
if arr[mid] >= target {
68+
right = mid
69+
} else {
70+
left = mid + 1
71+
}
72+
}
73+
74+
return left
75+
}

0 commit comments

Comments
 (0)