How to Sort Slice in Golang

1. Introduction

Sorting data is a common need in software development. In Go, the sort package provides several functions to sort slices of various basic types. This blog post will walk through sorting a slice of integers in ascending order using Go's sort package.

Definition

A slice in Go is a dynamically-sized, flexible view into the elements of an array. Sorting a slice involves rearranging its elements according to a specified order. The sort package's functions modify the slice in-place.

2. Program Steps

1. Create a slice of integers.

2. Use the sort.Ints function from the sort package to sort the slice.

3. Print the sorted slice.

3. Code Program

package main

import (
	"fmt"
	"sort"
)

func main() {
	// Step 1: Create a slice of integers
	numbers := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}

	// Step 2: Sort the slice using sort.Ints
	sort.Ints(numbers)

	// Step 3: Print the sorted slice
	fmt.Println("Sorted numbers:", numbers)
}

Output:

Sorted numbers: [1 1 2 3 3 4 5 5 5 6 9]

Explanation:

1. package main - Defines the package name for the Go program.

2. import "fmt" and import "sort" - Import the necessary packages. fmt is used for printing the output, and sort provides the sorting functionality.

3. numbers is a slice of unsorted integers.

4. sort.Ints(numbers) sorts the slice numbers in ascending order. It's worth noting that sort.Ints does not return a new slice; it sorts the original slice in place.

5. fmt.Println is used to print the sorted slice to verify the result.

6. The output confirms that the slice has been sorted in ascending order.


Comments