Esercizi di Go
Binary Search in Go
Find a value in a sorted slice by halving the search range at every step.
Cosa imparerai
- low, high and middle
- Returning -1 when missing
- Why it is fast
Search for 23
20
82
164
235
386
567
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.
Punti chiave
- The slice must be sorted.
- Each step throws away half.
- -1 means the value is not there.
Esempio Go eseguibile
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))
}
5
-1Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Numero Mancante Trova l'unico numero mancante da 0 a n. Facile
- K-th Smallest Element Find the k-th smallest value without fully sorting. Media