📜  检查给定的切片是否在 Golang 中排序

📅  最后修改于: 2021-10-24 14:20:12             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 语言中,您可以借助SliceIsSorted()函数检查给定的切片是否已排序。如果给定的切片已排序,则此函数返回 true。或者,如果给定的切片未排序,则返回 false。如果指定的接口不是切片类型,则此函数将发生恐慌。它是在 sort 包下定义的,因此您必须在程序中导入 sort 包才能访问 SliceIsSorted函数。

句法:

func SliceIsSorted(a_slice interface{}, less func(p, q int) bool) bool

例子:

// Go program to illustrate how to check
// the given slice is sorted or not
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // a structure
    Author := []struct {
        a_name    string
        a_article int
        a_id      int
    }{
        {"Mina", 304, 1098},
        {"Cina", 634, 102},
        {"Tina", 104, 105},
        {"Rina", 10, 108},
        {"Sina", 234, 103},
        {"Vina", 237, 106},
        {"Rohit", 56, 107},
        {"Mohit", 300, 104},
        {"Riya", 4, 101},
        {"Sohit", 20, 110},
    }
  
    // Sorting Author by their name
    // Using Slice() function
    sort.Slice(Author, func(p, q int) bool { 
     return Author[p].a_name < Author[q].a_name })
  
    // Checking the slice is sorted
    // according to their names
    // Using SliceIsSorted function
    res1 := sort.SliceIsSorted(Author, func(p, q int) bool { 
               return Author[p].a_name < Author[q].a_name })
      
    if res1 == true {
      
        fmt.Println("Slice is sorted by their names")
          
    } else {
      
        fmt.Println("Slice is not sorted by their names")
    }
  
    // Checking the slice is sorted 
    // according to their total articles
    // Using SliceIsSorted function
    res2 := sort.SliceIsSorted(Author, func(p, q int) bool { 
         return Author[p].a_article < Author[q].a_article })
      
    if res2 == true {
      
        fmt.Println("Slice is sorted by "+
         "their total number of articles")
          
    } else {
      
        fmt.Println("Slice is not sorted by"+
           " their total number of articles")
    }
  
    // Sorting Author by their ids
    // Using Slice() function
    sort.Slice(Author, func(p, q int) bool { 
      return Author[p].a_id < Author[q].a_id })
  
    // Checking the slice is sorted
    // according to their ids
    // Using SliceIsSorted function
    res3 := sort.SliceIsSorted(Author, func(p, q int) bool { 
                   return Author[p].a_id < Author[q].a_id })
      
    if res3 == true {
      
        fmt.Println("Slice is sorted by their ids")
          
    } else {
      
        fmt.Println("Slice is not sorted by their ids")
    }
}

输出:

Slice is sorted by their names
Slice is not sorted by their total number of articles
Slice is sorted by their ids