Skip to content

Commit 1dfbcd3

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

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
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+
// 左闭右开
30+
left := 0
31+
right := len(arr)
32+
for left < right {
33+
mid := left + (right-left)>>1
34+
if target == arr[mid] {
35+
return mid
36+
} else if target < arr[mid] {
37+
right = mid
38+
} else {
39+
left = mid + 1
40+
}
41+
}
42+
43+
return -1
44+
}
45+
46+
// BinarySearchRecursive performs binary search using recursion.
47+
// Returns the index of the target if found, or -1 if not found.
48+
func BinarySearchRecursive(arr []int, target int, left int, right int) int {
49+
// test 中是左闭右闭,因此按左闭右闭写
50+
if left > right {
51+
return -1
52+
}
53+
mid := left + (right-left)>>1
54+
if target == arr[mid] {
55+
return mid
56+
} else if target < arr[mid] {
57+
return BinarySearchRecursive(arr, target, left, mid-1)
58+
} else {
59+
return BinarySearchRecursive(arr, target, mid+1, right)
60+
}
61+
}
62+
63+
// FindInsertPosition returns the index where the target should be inserted
64+
// to maintain the sorted order of the array.
65+
func FindInsertPosition(arr []int, target int) int {
66+
// 左闭右开,终止时 left 和 right 等价
67+
left := 0
68+
right := len(arr)
69+
for left < right {
70+
mid := left + (right-left)>>1
71+
if target == arr[mid] {
72+
right = mid
73+
} else if target < arr[mid] {
74+
right = mid
75+
} else {
76+
left = mid + 1
77+
}
78+
}
79+
return left
80+
}

0 commit comments

Comments
 (0)