SoFunction
Updated on 2025-05-18

Go language uses slices package to easily implement sorting function

1. Built-in type sorting: application of strings and integers

1. Sorting string slices

Functions are a generic method that directly sorts string slices dictionary (from small to large). Here is a simple example:

package main

import (
    "fmt"
    "slices"
)

func main() {
    // Slice the string to be sorted    fruits := []string{"banana", "apple", "cherry"}
    // Perform sorting (modify slices in place)    (fruits)
    ("Sorted fruit list:", fruits) // Output: [apple banana cherry]}

Key points description

  • The sorting operation directly modifies the original slice without returning a new slice.
  • String sorting is based on the dictionary order of Unicode code points, such as uppercase letters will be placed before lowercase letters (such as “A” < “a”).

2. Integer slice sorting

For numerical types (e.g.intfloat64),It will be arranged in ascending order of numerical size:

package main

import (
    "fmt"
    "slices"
)

func main() {
    // Integer slices to be sorted    numbers := []int{34, 12, 45, 5}
    (numbers)
    ("Sorted integer list:", numbers) // Output: [5 12 34 45]}

Extended Description

  • Supports all implementationsTypes of interfaces, includingintfloat32stringrunewait.

  • If you need to sort in descending order, you can combine it

function:

(numbers)       // Sort ascending order first(numbers)    // Invert again to achieve descending order

2. Check the slice sorting status: Application of IsSorted Function

The function is used to determine whether the slice has been sorted in ascending order and returns a Boolean value. This is very useful in data verification or performance optimization scenarios:

package main

import (
    "fmt"
    "slices"
)

func main() {
    // Sort slices    sortedNums := []int{1, 3, 5, 7}
    ("Sorted:", (sortedNums)) // Output: true
    // Unsorted slices    unsortedStrs := []string{"z", "a", "m"}
    ("Sorted:", (unsortedStrs)) // Output: false}

Examples of usage scenarios

  • Before multiple sorting operations, passIsSortedDetermine whether the sort needs to be performed to avoid invalid calculations.
  • Verify that the order of external data (such as file reading, API return) is as expected.

3. Principles and best practices

1. Sorting algorithm and performance

slicesThe bottom layer of the package sorting uses the ** Quicksort** algorithm, with a time complexity of O (n log n), which is suitable for most scenarios. For small-scale slices (such as length less than 12), the insert sort is automatically switched to optimize constant time.

2. Things to note

original := []int{2, 4, 1}
copy := (original) // Create a copy(copy)
  • User-defined type sorting: If you need to sort custom types such as structures, you need to implement themInterface (includingLenLessSwapMethod), or usesortPackage's non-generic interface (compatibility scheme before Go 1.18).

4. Summary

passslicesPackage, Go language implements concise and efficient sorting functions, and one line of code can complete the sorting and verification of built-in types. Core methods include:

  • (slice): Sort the slices ascendingly (modify them in place).
  • (slice): Check whether the slices are arranged in ascending order.

Rational use of these tools can significantly improve the readability and development efficiency of the code. For complex sorting requirements (such as custom comparison logic), you can combine them withorsortThe package is further expanded.

Sample code running results

Sort fruit list: [apple banana cherry]
Sorted integer list: [5 12 34 45]
Whether it has been sorted: true
Whether it has been sorted: false

This is the article about how to easily implement the sorting function using the slices package in Go language. For more related content of Go slices sorting function, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!