Skip to content

Commit 10bff4d

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

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
for i, v := range arr {
30+
if v == target {
31+
return i
32+
}
33+
}
34+
return -1
35+
}
36+
37+
// BinarySearchRecursive performs binary search using recursion.
38+
// Returns the index of the target if found, or -1 if not found.
39+
func BinarySearchRecursive(arr []int, target int, left int, right int) int {
40+
if left > right {
41+
return -1
42+
}
43+
mid := (left + right) / 2
44+
if arr[mid] == target {
45+
return mid
46+
}
47+
if arr[mid] > target {
48+
return BinarySearchRecursive(arr, target, left, mid-1)
49+
}
50+
return BinarySearchRecursive(arr, target, mid+1, right)
51+
}
52+
53+
// FindInsertPosition returns the index where the target should be inserted
54+
// to maintain the sorted order of the array.
55+
func FindInsertPosition(arr []int, target int) int {
56+
if arr == nil || len(arr) == 0 {
57+
return 0
58+
}
59+
60+
for i, v := range arr {
61+
if v >= target {
62+
return i
63+
}
64+
}
65+
return len(arr)
66+
}

0 commit comments

Comments
 (0)