Skip to content

Commit

Permalink
Merge 10d9201 into 5222eb6
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed May 20, 2019
2 parents 5222eb6 + 10d9201 commit 971efd5
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,4 @@ problems from
* [Day 268](https://github.com/vaskoz/dailycodingproblem-go/issues/544)
* [Day 269](https://github.com/vaskoz/dailycodingproblem-go/issues/547)
* [Day 270](https://github.com/vaskoz/dailycodingproblem-go/issues/548)
* [Day 271](https://github.com/vaskoz/dailycodingproblem-go/issues/553)
29 changes: 29 additions & 0 deletions day271/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day271

import "sort"

// BinarySearch is a handwritten binary search.
func BinarySearch(sorted []int, x int) int {
left, right := 0, len(sorted)-1
for left < right {
mid := (left + right) / 2
val := sorted[mid]
if x < val {
right = mid - 1
} else if x == val {
return mid
} else {
left = mid + 1
}
}
return -1
}

// BinarySearchSortPkg delegates to the sort package.
func BinarySearchSortPkg(sorted []int, x int) int {
index := sort.SearchInts(sorted, x)
if sorted[index] == x {
return index
}
return -1
}
47 changes: 47 additions & 0 deletions day271/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package day271

import "testing"

// nolint
var testcases = []struct {
sorted []int
x int
contains bool
}{
{[]int{1, 10, 11, 12, 14, 15}, 11, true},
{[]int{1, 10, 11, 12, 14, 15}, 7, false},
}

func TestBinarySearch(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if index := BinarySearch(tc.sorted, tc.x); (index > 0) != tc.contains {
t.Errorf("TCID %d, expected %v, got %v", tcid, tc.contains, (index > 0))
}
}
}

func BenchmarkBinarySearch(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BinarySearch(tc.sorted, tc.x)
}
}
}

func TestBinarySearchSortPkg(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if index := BinarySearchSortPkg(tc.sorted, tc.x); (index >= 0) != tc.contains {
t.Errorf("TCID %d, expected %v, got %v", tcid, tc.contains, (index > 0))
}
}
}

func BenchmarkBinarySearchSortPkg(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BinarySearchSortPkg(tc.sorted, tc.x)
}
}
}

0 comments on commit 971efd5

Please sign in to comment.