Skip to content

Commit 311f96d

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

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
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+
if len(arr) == 0 {
30+
return -1
31+
}
32+
33+
left := 0
34+
right := len(arr) - 1
35+
36+
for left <= right {
37+
index := (left + right) / 2
38+
val := arr[index]
39+
40+
if val == target {
41+
return index
42+
}
43+
44+
if val > target {
45+
right = index - 1
46+
} else {
47+
left = index + 1
48+
}
49+
}
50+
51+
return -1
52+
}
53+
54+
// BinarySearchRecursive performs binary search using recursion.
55+
// Returns the index of the target if found, or -1 if not found.
56+
func BinarySearchRecursive(arr []int, target int, left int, right int) int {
57+
if len(arr) == 0 {
58+
return -1
59+
}
60+
61+
if left > right {
62+
return -1
63+
}
64+
65+
index := (left + right) / 2
66+
val := arr[index]
67+
68+
if val == target {
69+
return index
70+
}
71+
72+
if val > target {
73+
return BinarySearchRecursive(arr, target, left, index - 1)
74+
} else {
75+
return BinarySearchRecursive(arr, target, index + 1, right)
76+
}
77+
}
78+
79+
// FindInsertPosition returns the index where the target should be inserted
80+
// to maintain the sorted order of the array.
81+
func FindInsertPosition(arr []int, target int) int {
82+
if len(arr) == 0 {
83+
return 0
84+
}
85+
86+
left := 0
87+
right := len(arr) - 1
88+
89+
for left <= right {
90+
index := (left + right) / 2
91+
val := arr[index]
92+
93+
if val == target {
94+
return index
95+
}
96+
97+
if val < target {
98+
left = index + 1
99+
} else {
100+
right = index - 1
101+
}
102+
}
103+
104+
return left
105+
}

0 commit comments

Comments
 (0)