¿Cómo ordenar una porción de enteros en Golang?

El segmento de lenguaje de Go es más poderoso, flexible y conveniente que una array y es una estructura de datos liviana. El segmento es una secuencia de longitud variable que almacena elementos de un tipo similar, no está permitido almacenar diferentes tipos de elementos en el mismo segmento.
El idioma de Go le permite ordenar los elementos del sector según su tipo. Entonces, un segmento de tipo int se ordena usando las siguientes funciones. Estas funciones se definen en el paquete de clasificación, por lo que debe importar el paquete de clasificación en su programa para acceder a estas funciones:

1. Ints: esta función se usa para ordenar solo una porción de enteros y ordena los elementos de la porción en orden creciente.

Sintaxis:

func Ints(slc []int)

Aquí, slc representa una porción de enteros. Analicemos este concepto con la ayuda de un ejemplo:

Ejemplo:

// Go program to illustrate how 
// to sort the slice of ints
package main
   
import (
    "fmt"
    "sort"
)
   
// Main function
func main() {
       
    // Creating and initializing slices
    // Using shorthand declaration
    scl1 := []int{400, 600, 100, 300, 500, 200, 900}
    scl2 := []int{-23, 567, -34, 67, 0, 12, -5}
       
    // Displaying slices
    fmt.Println("Slices(Before):")
    fmt.Println("Slice 1: ", scl1)
    fmt.Println("Slice 2: ", scl2)
       
    // Sorting the slice of ints
    // Using Ints function
    sort.Ints (scl1)
    sort.Ints (scl2)
       
    // Displaying the result
    fmt.Println("\nSlices(After):")
    fmt.Println("Slice 1 : ", scl1)
    fmt.Println("Slice 2 : ",scl2)
}

Producción:

Slices(Before):
Slice 1:  [400 600 100 300 500 200 900]
Slice 2:  [-23 567 -34 67 0 12 -5]

Slices(After):
Slice 1 :  [100 200 300 400 500 600 900]
Slice 2 :  [-34 -23 -5 0 12 67 567]

2. IntsAreSorted: esta función se utiliza para comprobar si el segmento dado de enteros está ordenado (en orden creciente) o no. Este método devuelve verdadero si el segmento está ordenado, o devuelve falso si el segmento no está ordenado.

Sintaxis:

func IntsAreSorted(scl []int) bool

Aquí, scl representa una porción de ints . Analicemos este concepto con la ayuda de un ejemplo:

Ejemplo:

// Go program to illustrate how to check
// whether the given slice of ints is in
// sorted form or not
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing slices
    // Using shorthand declaration
    scl1 := []int{100, 200, 300, 400, 500, 600, 700}
    scl2 := []int{-23, 567, -34, 67, 0, 12, -5}
  
    // Displaying slices
    fmt.Println("Slices:")
    fmt.Println("Slice 1: ", scl1)
    fmt.Println("Slice 2: ", scl2)
  
    // Checking the slice is in sorted form or not
    // Using IntsAreSorted function
    res1 := sort.IntsAreSorted(scl1)
    res2 := sort.IntsAreSorted(scl2)
  
    // Displaying the result
    fmt.Println("\nResult:")
    fmt.Println("Is Slice 1 is sorted?: ", res1)
    fmt.Println("Is Slice 2 is sorted?: ", res2)
}

Producción:

Slices:
Slice 1:  [100 200 300 400 500 600 700]
Slice 2:  [-23 567 -34 67 0 12 -5]

Result:
Is Slice 1 is sorted?:  true
Is Slice 2 is sorted?:  false

Publicación traducida automáticamente

Artículo escrito por ankita_saini 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 *