Ejercicios de Go

Binary Search in Go

Find a value in a sorted slice by halving the search range at every step.

  • Principiante
  • 3 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • low, high and middle
  • Returning -1 when missing
  • Why it is fast
Search for 23
20
82
164
235
386
567
Found at index 5 after three steps.

Halve the range each step

Binary search looks at the middle of a sorted list and throws away the half that cannot contain the target. Each step halves the work, so it is very fast on large lists.

low and high mark the part that is still being searched. The function returns the position of the target, or -1 when the range becomes empty. low + (high-low)/2 finds the middle without overflow.

Puntos clave

  1. The slice must be sorted.
  2. Each step throws away half.
  3. -1 means the value is not there.

Ejemplo ejecutable de Go

Go
Ejecutar código →
main.go
package main

import "fmt"

func binarySearch(items []int, target int) int {
	low, high := 0, len(items)
	for low < high {
		middle := low + (high-low)/2
		switch {
		case items[middle] == target:
			return middle
		case items[middle] < target:
			low = middle + 1
		default:
			high = middle
		}
	}
	return -1
}

func main() {
	sorted := []int{2, 5, 8, 12, 16, 23, 38, 56}
	fmt.Println(binarySearch(sorted, 23))
	fmt.Println(binarySearch(sorted, 7))
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
5
-1

Practica

Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.

¿Terminaste esta lección?

Márcala como aprendida para seguir tu progreso.

Practica con un reto

Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.

Todos los retos