¿Cómo ordenar una porción de búsqueda en Golang?

El lenguaje Go proporciona una implementación de soporte incorporada de constantes básicas y reflexión en tiempo de ejecución para operar el paquete de ordenación. Golang tiene la capacidad de que las funciones se ejecuten independientemente unas de otras. Con la ayuda de esta función, podemos ordenar fácilmente enteros y strings importando el paquete «ordenar» . Estas funciones se definen en el paquete de clasificación, por lo que debe importar el paquete de clasificación en su programa. La función de clasificación puede buscar cualquier lista de funciones de clasificación importantes de Golang de la siguiente manera:

Sintaxis:

func Search(n int, f func(int) bool) int

Valor devuelto: esta función devuelve el índice i más pequeño en [0, n) en el que f(i) es verdadero, suponiendo que en el rango [0, n), f(i) == verdadero implica f(i+1) == cierto.

Esta función se usa para ordenar solo una parte de la búsqueda. Los siguientes ejemplos ilustran el uso del método anterior en Golang:

Ejemplo 1:

package main
  
import (
    "fmt"
    "sort"
)
  
func main() {
  
    // integer slice in unsort order
    intSlice := []int{10, 3, 6, 10, 15, 21, 38, 26, 25, 45}
    a := 15
    pos := sort.SearchInts(intSlice, a)
    fmt.Printf("Found %d at index %d in %v\n", a, pos, intSlice)
  
    // string slice in unsorted order
    strSlice := []string{"Pink", "Orange", 
                         "Green", "Black", 
                  "Purple", "Blue", "Red"}
      
    b := "Green"
    pos = sort.SearchStrings(strSlice, b)
    fmt.Printf("Found %s at index %d in %v\n",
                             b, pos, strSlice)
  
    // string slice in unsorted order
    fltSlice := []float64{612.15, 114.510,
               211.144, 396.242, 485.143}
      
    c := 211.144
    pos = sort.SearchFloat64s(fltSlice, c)
    fmt.Printf("Found %f at index %d in %v\n",
                            c, pos, fltSlice)
  
    // sorted slice in descending
    d := []int{45, 38, 26, 25, 21, 15, 10, 10, 6, 3}
    e := 38
    i := sort.Search(len(d), func(i int) bool { return d[i] <= e })
      
    if i < len(d) && d[i] == e {
        fmt.Printf("found %d at index %d in %v\n", e, i, d)
    } else {
        fmt.Printf("%d not found in %v\n", e, d)
    }
}

Producción:

Found 15 at index 4 in [10 3 6 10 15 21 38 26 25 45]
Found Green at index 6 in [Pink Orange Green Black Purple Blue Red]
Found 211.144000 at index 2 in [612.15 114.51 211.144 396.242 485.143]
found 38 at index 1 in [45 38 26 25 21 15 10 10 6 3]

Ejemplo 2: El ejemplo dado ilustra la búsqueda en una lista ordenada en orden ascendente en diferentes formas.

package main
  
import (
    "fmt"
    "sort"
)
  
func main() {
  
    // unsorted
    s := []int{19, 42, 24, 63, -20, 59}
    sort.Sort(sort.IntSlice(s))
  
    // sorted
    fmt.Println(s)
    fmt.Println("Length of Slice: ", sort.IntSlice.Len(s))
  
    fmt.Println("40 found in Slice at position: ",
        sort.IntSlice(s).Search(40))
  
    fmt.Println("-10 found in Slice at position: ",
        sort.IntSlice(s).Search(6))
    fmt.Println("-----------------------------------")
  
    t := []string{"Pink", "Orange", "Green",
        "Black", "Purple", "Blue", "Red"}
  
    sort.Sort(sort.StringSlice(t))
  
    fmt.Println(t)
    fmt.Println("Length of Slice: ", sort.StringSlice.Len(t))
  
    fmt.Println("Black found in Slice at position: ",
        sort.StringSlice(t).Search("Black"))
  
    fmt.Println("Orange found in Slice at position: ",
        sort.StringSlice(t).Search("Orange"))
  
    fmt.Println("-----------------------------------")
  
    // unsorted
    u := []float64{602.15, 194.10, 611.144, 396.42, 655.433}
    sort.Sort(sort.Float64Slice(u))
  
    // sorted
    fmt.Println(u)
    fmt.Println("Length of Slice: ", sort.Float64Slice.Len(u))
  
    fmt.Println("611.144 found in Slice at position: ",
        sort.Float64Slice(u).Search(611.144))
  
    fmt.Println("194.10 found in Slice at position: ",
        sort.Float64Slice(u).Search(194.10))
}

Producción:

[-20 19 24 42 59 63]
Length of Slice:  6
40 found in Slice at position:  3
-10 found in Slice at position:  1
-----------------------------------
[Black Blue Green Orange Pink Purple Red]
Length of Slice:  7
Black found in Slice at position:  0
Orange found in Slice at position:  3
-----------------------------------
[194.1 396.42 602.15 611.144 655.433]
Length of Slice:  5
611.144 found in Slice at position:  3
194.10 found in Slice at position:  0

Publicación traducida automáticamente

Artículo escrito por shivanisinghss2110 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *