Skip to content

Instantly share code, notes, and snippets.

@emre
Last active October 13, 2020 23:10
Show Gist options
  • Save emre/6340638 to your computer and use it in GitHub Desktop.
Save emre/6340638 to your computer and use it in GitHub Desktop.
binary search implementation on golang slices
package main
import (
"fmt"
)
func BinarySearch(target_map []int, value int) int {
start_index := 0
end_index := len(target_map) - 1
for start_index <= end_index {
median := (start_index + end_index) / 2
if target_map[median] < value {
start_index = median + 1
} else {
end_index = median - 1
}
}
if start_index == len(target_map) || target_map[start_index] != value {
return -1
} else {
return start_index
}
}
func main() {
values := []int{1, 2, 3, 4, 5, 6, 7}
fmt.Println(BinarySearch(values, 5))
}
@porjo
Copy link

porjo commented Sep 22, 2013

  1. That's a slice not a map
  2. if you're using slices, why not use the built-in sort.Search() ?

@emre
Copy link
Author

emre commented Sep 23, 2013

  1. That's a slice not a map

Fixed. I don't know what was I thinking.

  1. if you're using slices, why not use the built-in sort.Search() ?

I was just practicing golang.

@hoahm-ts
Copy link

hoahm-ts commented Dec 20, 2017

In the 14th-row, I think we should improve a little bit to avoid memory overflow:

median := start_index + (end_index - start_index) / 2

@AndrewWPhillips
Copy link

AndrewWPhillips commented Feb 7, 2019

I think this is simpler but not sure if it's correct (untested):

start_index := 0
end_index := len(target_map)

for start_index < end_index {
	median := start_index + (end_index - start_index) / 2
	if target_map[start_index] == value {
		return start_index
	}
	if target_map[median] < value {
		start_index = median
	} else {
		end_index = median
	}
}

return -1

@rakesh-ideal
Copy link

./main.go:19:4: too many arguments to return

I think this is simpler but not sure if it's correct (untested):

start_index := 0
end_index := len(target_map)

for start_index < end_index {
	median := start_index + (end_index - start_index) / 2
	if target_map[start_index] == value {
		return start_index
	}
	if target_map[median] < value {
		start_index = median
	} else {
		end_index = median
	}
}

return -1

./main.go:19:4: too many arguments to return

@hgisinger
Copy link

func binarySearch(arr []int, val int) int {
	first := 0
	last := len(arr) - 1

	for first <= last {
		mid := (first + last) / 2
		switch {
		case arr[mid] == val:
			return mid
		case arr[mid] < val:
			first = mid + 1
		case arr[mid] > val:
			last = mid - 1
		}
	}
	return -1
}

@cherednichenkoa
Copy link

You can additionally add validation in case if array of given elements is not sorted for sure

if !sort.IntsAreSorted(target_map) { panic("Given array is not sorted") }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment