Skip to content

Instantly share code, notes, and snippets.

@brenogcota
Last active September 18, 2022 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brenogcota/9f6b66f48a378fc172477a37b0bbecb9 to your computer and use it in GitHub Desktop.
Save brenogcota/9f6b66f48a378fc172477a37b0bbecb9 to your computer and use it in GitHub Desktop.
Example binary search in Javascript and Go

Binary Search

Example Binary search in Javascript and Go

Javascript

function BinarySearch(array, number) {
	var minIndex = 0
	var maxIndex = array.length - 1
	while (minIndex <= maxIndex) {
		var midIndex = Math.floor((maxIndex + minIndex) / 2)
		var midItem = array[midIndex]
		if (number == midItem) {
                        minIndex = maxIndex + 1
			return midIndex
		}
		if (midItem < number) {
			minIndex = midIndex + 1
		} else if (midItem > number) {
			maxIndex = midIndex - 1
		}
	}
	return -1
}

Golang

func BinarySearch(array []int, number int) int {
	minIndex := 0
	maxIndex := len(array) - 1
	for minIndex <= maxIndex {
		midIndex := int((maxIndex + minIndex) / 2)
		midItem := array[midIndex]
		if number == midItem {
			return midIndex
		}
		if midItem < number {
			minIndex = midIndex + 1
		} else if midItem > number {
			maxIndex = midIndex - 1
		}
	}
	return -1
}

Learn more about data structures in Go: ua-nick/Data-Structures-and-Algorithms

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