Golang 如何对float64s的slice进行排序

Golang 如何对float64s的slice进行排序

在Go语言中slice比数组更强大、更灵活、更方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。Go语言允许你根据其类型对片断的元素进行排序。因此,一个float64类型的片断可以通过使用以下函数进行排序。这些函数是在sort包中定义的,所以你必须在你的程序中导入sort包来访问这些函数。

1.Float64s: 该函数仅用于对float64s的片断进行排序,它将片断中的元素按递增顺序进行排序。

语法

func Float64s(slc []float64)
Go

这里,slc代表float64的一个片断。让我们借助于一个例子来讨论这个概念。

例子

// Go program to illustrate how
// to sort a slice of float64s
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing slices
    // Using shorthand declaration
    scl1 := []float64{9.56, 4.56, 2.4,
                 10, 43, 0.56, 35.246}
      
    scl2 := []float64{38.32, -32.23, 
               -45.56, 23.45, -0.43}
  
    // Displaying slices
    fmt.Println("Slice(Before):")
    fmt.Println("Slice 1: ", scl1)
    fmt.Println("Slice 2: ", scl2)
  
    // Sorting the elements of the slice
    // Using Float64s function
    sort.Float64s(scl1)
    sort.Float64s(scl2)
  
    // Displaying the result
    fmt.Println("\nSlice(After):")
    fmt.Println("Slice 1: ", scl1)
    fmt.Println("Slice 2: ", scl2)
}
Go

输出

Slice(Before):
Slice 1:  [9.56 4.56 2.4 10 43 0.56 35.246]
Slice 2:  [38.32 -32.23 -45.56 23.45 -0.43]

Slice(After):
Slice 1:  [0.56 2.4 4.56 9.56 10 35.246 43]
Slice 2:  [-45.56 -32.23 -0.43 23.45 38.32]
Go

2.Float64sAreSorted: 该函数用于检查给定的浮点数片断是否为排序形式(按递增顺序)。如果该片处于排序状态,则该方法返回true;如果该片不处于排序状态,则返回false。

语法

func Float64sAreSorted(scl []float64) bool
Go

在这里,scl代表一个float64s的切片。让我们借助于一个例子来讨论这个概念。

例子

// Go program to illustrate how to check whether the
// given slice of float64 is in sorted form or not
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing slices
    // Using shorthand declaration
    scl1 := []float64{9.56, 4.56, 2.4,
                 10, 43, 0.56, 35.246}
      
    scl2 := []float64{-45.56, -32.23,
                 -0.43, 23.45, 38.32}
  
    // 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 Float64sAreSorted  function
    res1 := sort.Float64sAreSorted(scl1)
    res2 := sort.Float64sAreSorted(scl2)
  
    // Displaying the result
    fmt.Println("\nResult:")
    fmt.Println("Is Slice 1 is sorted?: ", res1)
    fmt.Println("Is Slice 2 is sorted?: ", res2)
}
Go

输出

Slices:
Slice 1:  [9.56 4.56 2.4 10 43 0.56 35.246]
Slice 2:  [-45.56 -32.23 -0.43 23.45 38.32]

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册