🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of fscotto

fscotto's solution

to Binary Search in the Go Track

Published at Mar 28 2021 · 0 comments
Instructions
Test suite
Solution

Implement a binary search algorithm.

Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.

If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.

In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.

In each step, the algorithm compares the search key value with the key value of the middle element of the array.

If the keys match, then a matching element has been found and its index, or position, is returned.

Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.

If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Coding the solution

Look for a stub file having the name binary_search.go and place your solution code in that file.

Running the tests

To run the tests run the command go test from within the exercise directory.

If the test suite contains benchmarks, you can run these with the --bench and --benchmem flags:

go test -v --bench . --benchmem

Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary.

Further information

For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io Go language page.

Source

Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

binary_search_test.go

package binarysearch

import (
	"fmt"
	"math/rand"
	"testing"
)

func TestSearchInts(t *testing.T) {
	for _, test := range testCases {
		if x := SearchInts(test.slice, test.key); x != test.x {
			t.Fatalf("FAIL: %s\nSearchInts(%#v, %d) = %d, want %d",
				test.description, test.slice, test.key, x, test.x)
		}
		t.Logf("SUCCESS: %s", test.description)
	}
}

// Benchmarks also test searching larger random slices

type query struct {
	slice []int
	x     int
}

func newQuery(n int) (query, error) {
	q := query{slice: make([]int, n)}
	for i := 0; i < n; i++ {
		q.slice[i] = i
	}
	q.x = rand.Intn(n)
	if res := SearchInts(q.slice, q.x); res != q.x {
		return q, fmt.Errorf("Search of %d values gave different answer", n)
	}
	return q, nil
}

func runBenchmark(n int, b *testing.B) {
	q, err := newQuery(n)
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		SearchInts(q.slice, q.x)
	}
}

func Benchmark1e2(b *testing.B) { runBenchmark(1e2, b) }
func Benchmark1e4(b *testing.B) { runBenchmark(1e4, b) }
func Benchmark1e6(b *testing.B) { runBenchmark(1e6, b) }
func Benchmark1e8(b *testing.B) { runBenchmark(1e8, b) }

cases_test.go

package binarysearch

// Source: exercism/problem-specifications
// Commit: bfb218f binary-search: test description tweak
// Problem Specifications Version: 1.3.0

var testCases = []struct {
	description string
	slice       []int
	key         int
	x           int
	err         string
}{
	{
		description: "finds a value in an array with one element",
		slice:       []int{6},
		key:         6,
		x:           0,
		err:         "",
	},
	{
		description: "finds a value in the middle of an array",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         6,
		x:           3,
		err:         "",
	},
	{
		description: "finds a value at the beginning of an array",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         1,
		x:           0,
		err:         "",
	},
	{
		description: "finds a value at the end of an array",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         11,
		x:           6,
		err:         "",
	},
	{
		description: "finds a value in an array of odd length",
		slice:       []int{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634},
		key:         144,
		x:           9,
		err:         "",
	},
	{
		description: "finds a value in an array of even length",
		slice:       []int{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377},
		key:         21,
		x:           5,
		err:         "",
	},
	{
		description: "identifies that a value is not included in the array",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         7,
		x:           -1,
		err:         "value not in array",
	},
	{
		description: "a value smaller than the array's smallest value is not found",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         0,
		x:           -1,
		err:         "value not in array",
	},
	{
		description: "a value larger than the array's largest value is not found",
		slice:       []int{1, 3, 4, 6, 8, 9, 11},
		key:         13,
		x:           -1,
		err:         "value not in array",
	},
	{
		description: "nothing is found in an empty array",
		slice:       []int{},
		key:         1,
		x:           -1,
		err:         "value not in array",
	},
	{
		description: "nothing is found when the left and right bounds cross",
		slice:       []int{1, 2},
		key:         0,
		x:           -1,
		err:         "value not in array",
	},
}
package binarysearch

// SearchInts perform binary search on a list of ints
func SearchInts(numbers []int, key int) int {
	low, high := 0, len(numbers)-1
	for low <= high {
		middle := (low + high) / 2
		n := numbers[middle]
		switch {
		case n == key:
			return middle
		case key < n:
			high = middle - 1
		case key > n:
			low = middle + 1
		}
	}
	return -1
}

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?