How to sort an int slice in Golang

In this shot, we will learn how to sort a slice of ints using Golang.

Slice is a dynamically-sized array in Golang.

We can sort the slice of ints in Golang with the Ints() function, which is provided by the sort package.

Syntax

sort.Ints(slice_of_ints)

Parameters

This function takes a slice as a parameter.

Return value

This function does not return anything because it sorts the slice in place.

Example

In the following example, we will try to sort the slice of ints.

Code

package main
//import packages
import(
"fmt"
"sort"
)
//program execution starts from here
func main(){
//Declare and initialize slice
n := []int{23, 12, 98, 45, 88, 36}
//Display slice before sorting
fmt.Println("Before : ", n)
//sort the slice
sort.Ints(n)
//Display slice after sorting
fmt.Println("After : ", n)
}

Explanation

In the code snippet given above:

  • Lines 5–6: We import the following packages:

    • fmt: The format package is useful for printing slices.
    • sort: The ints() function is provided by the sort package.
  • Line 10: The program execution starts from the main() function.

  • Line 13: We declare and initialize the slice of ints, n.

  • Line 16: We display the slice n before sorting it.

  • Line 19: We sort the slice n by passing it as a parameter to the Ints() function. This action will change the original slice.

  • Line 22: We display the slice n after sorting it.

Free Resources