如何在 Golang 中對 int 切片進行排序?


在許多應用程式中,對 int 值的切片進行排序是一項常見任務,Go 提供了一個內建的 sort 包,其中包含用於對任何型別切片進行排序的函式,包括 int 值的切片。在本文中,我們將討論如何在 Golang 中對 int 值的切片進行排序。

為了在 Go 中對 int 值的切片進行排序,我們可以使用 sort 包提供的 sort.Ints() 函式。以下是如何使用此函式的示例:

示例

package main

import (
   "fmt"
   "sort"
)

func main() {
   s := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("Original slice:", s)

   sort.Ints(s)

   fmt.Println("Sorted slice:", s)
}

輸出

Original slice: [5 2 6 3 1 4]
Sorted slice: [1 2 3 4 5 6]

在上面的示例中,我們建立了一個 int 值的切片,其值為 5、2、6、3、1 和 4。然後,我們使用 sort.Ints() 函式按升序對切片進行排序。該函式以 int 值的切片作為引數,並就地對切片進行排序。

如果我們想按降序對切片進行排序,我們可以使用 sort.Sort() 函式和 sort.Interface 介面的自定義實現。以下是如何執行此操作的示例:

示例

package main

import (
   "fmt"
   "sort"
)

type IntSlice []int

func (s IntSlice) Len() int {
   return len(s)
}

func (s IntSlice) Swap(i, j int) {
   s[i], s[j] = s[j], s[i]
}

func (s IntSlice) Less(i, j int) bool {
   return s[i] > s[j]
}

func main() {
   s := IntSlice{5, 2, 6, 3, 1, 4}
   fmt.Println("Original slice:", s)

   sort.Sort(s)

   fmt.Println("Sorted slice:", s)
}

輸出

Original slice: [5 2 6 3 1 4]
Sorted slice: [6 5 4 3 2 1]

在上面的示例中,我們定義了一個自定義型別 IntSlice,它表示 int 值的切片。然後,我們透過定義 Len()、Swap() 和 Less() 方法,為該型別實現了 sort.Interface 介面。最後,我們使用此自定義型別建立了一個 int 值的切片,並使用 sort.Sort() 函式按降序對切片進行排序。

結論

在 Golang 中對 int 值的切片進行排序很容易,可以使用 sort 包提供的 sort.Ints() 函式來完成。如果我們想按降序對切片進行排序,我們可以定義 sort.Interface 介面的自定義實現,並使用 sort.Sort() 函式。瞭解如何對 int 值的切片進行排序對於編寫高效且有效的 Go 程式碼至關重要。

更新於: 2023年4月25日

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告