Exercices Go

Binary Search in Go

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

  • Débutant
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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.

Points clés

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

Exemple Go exécutable

Go
Exécuter le code →
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))
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
5
-1

S'entraîner

Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis