个性化阅读
专注于IT技术分析

如何在Golang中对整数进行排序?

在Go语言中,slice比数组更强大、更灵活、更方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储类似类型的元素,不允许在同一个slice中存储不同类型的元素。

Go语言允许你根据切片的类型对切片的元素进行排序。因此, 使用以下函数对int类型切片进行排序。这些功能是在sort包下定义的, 因此, 你必须在程序中导入sort包才能访问这些功能:

1.整数:此函数仅用于对一个int切片进行排序, 并按升序对切片中的元素进行排序。

语法如下:

func Ints(slc []int)

这里, slc代表一片整数。让我们借助示例来讨论这个概念:

例子:

//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)
}

输出如下:

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:此函数用于检查给定的int切片是否为排序形式(升序)。如果切片为排序形式, 则此方法返回true;否则, 如果切片未为排序形式, 则返回false。

语法如下:

func IntsAreSorted(scl []int) bool

这里, scl代表一片整数。让我们借助示例来讨论这个概念:

例子:

//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)
}

输出如下:

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

赞(0)
未经允许不得转载:srcmini » 如何在Golang中对整数进行排序?

评论 抢沙发

评论前必须登录!