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 packagesimport("fmt""sort")//program execution starts from herefunc main(){//Declare and initialize slicen := []int{23, 12, 98, 45, 88, 36}//Display slice before sortingfmt.Println("Before : ", n)//sort the slicesort.Ints(n)//Display slice after sortingfmt.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
nbefore sorting it. -
Line 19: We sort the slice
nby passing it as a parameter to theInts()function. This action will change the original slice. -
Line 22: We display the slice
nafter sorting it.