Estos últimos meses he tenido la oportunidad de trabajar con Go y he encontrado funcionalidades interesantes, entre ellas la función sort.Search
la cual nos da acceso a un algoritmo de busqueda binaria, actualmente el paquete sort ofrece tres funciones mas SearchInts
, SearchFloat64s
y SearchStrings
las cuales terminan utilizando sort.Search
.
Algo que se debe tomar en cuenta es que para utilizar cualquiera de estos métodos es necesario que el listado de elementos sea ordendo previamente de forma ascendente o descendente, también que si eliges ordenar la lista de forma descendente debes cambiar la forma en que se valida de >=
a <=
.
Ahora veamos algunos ejemplos de como utilizar la función sort.Search
y sort.SearchInts
en el que buscaremos el número 100 en un conjunto de números generados al azar.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package main
import (
"log"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
max := rand.Intn(1000)
var nums []int
for i := 0; i < max; i++ {
nums = append(nums, rand.Intn(200))
}
sort.Ints(nums)
idToSearch := 100
i := sort.Search(len(nums), func(i int) bool { return nums[i] >= idToSearch })
if i < len(nums) && nums[i] == idToSearch {
log.Print(nums)
log.Printf("the num %d was found with the index %d", 100, i)
} else {
log.Print("id was not found")
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package main
import (
"log"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
max := rand.Intn(1000)
var nums []int
for i := 0; i < max; i++ {
nums = append(nums, rand.Intn(200))
}
sort.Ints(nums)
idToSearch := 100
i := sort.SearchInts(nums, idToSearch)
if i < len(nums) && nums[i] == idToSearch {
log.Print(nums)
log.Printf("the num %d was found with the index %d", 100, i)
} else {
log.Print("id was not found")
}
}
|
Happy coding! @SaturPimentel