Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 7, 2019 16:36
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 parzibyte/21c46910901047adcaa61247c6468fe8 to your computer and use it in GitHub Desktop.
Save parzibyte/21c46910901047adcaa61247c6468fe8 to your computer and use it in GitHub Desktop.
func busquedaBinaria(arreglo []int, busqueda int) (indice int) {
izquierda := 0
derecha := len(arreglo) - 1
/*
Recordemos que For is Go's "while"
https://tour.golang.org/flowcontrol/3
*/
for izquierda <= derecha {
indiceDelMedio := int(math.Floor((float64(izquierda+derecha) / 2)))
elementoDelMedio := arreglo[indiceDelMedio]
if elementoDelMedio == busqueda {
return indiceDelMedio
}
if busqueda < elementoDelMedio {
derecha = indiceDelMedio - 1
} else {
izquierda = indiceDelMedio + 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment