Skip to content

Commit 8b698d6

Browse files
authored
Merge pull request #27 from rihib/binary_search
Binary Search
2 parents 9e15eb4 + 9419f2d commit 8b698d6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

pullrequests/binary_search/step1.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package binarysearch
3+
4+
/*
5+
時間:5分
6+
単なる二分探索だが、まだ少し実装がもたつく部分があり、体に定着するほどにはなっていないなと思いました。
7+
*/
8+
func binarySearchHalfClosed(nums []int, target int) int {
9+
left, right := 0, len(nums)
10+
for left < right {
11+
mid := left + (right-left)/2
12+
if nums[mid] == target {
13+
return mid
14+
}
15+
if target < nums[mid] {
16+
right = mid
17+
} else {
18+
left = mid + 1
19+
}
20+
}
21+
return -1
22+
}
23+
24+
func binarySearchClosed(nums []int, target int) int {
25+
left, right := 0, len(nums)-1
26+
for left <= right {
27+
mid := left + (right-left)/2
28+
if nums[mid] == target {
29+
return mid
30+
}
31+
if target < nums[mid] {
32+
right = mid - 1
33+
} else {
34+
left = mid + 1
35+
}
36+
}
37+
return -1
38+
}

pullrequests/binary_search/step2.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package binarysearch
3+
4+
import "sort"
5+
6+
/*
7+
PythonのbisectみたいなものがGoにもないかと調べたところ、sort.Search関数が使えそうだったので実装してみました。
8+
*/
9+
func search(nums []int, target int) int {
10+
index := sort.Search(len(nums), func(i int) bool {
11+
return nums[i] >= target
12+
})
13+
if index < len(nums) && nums[index] == target {
14+
return index
15+
}
16+
return -1
17+
}

0 commit comments

Comments
 (0)