Sling Academy
Home/Golang/Sorting a slice of integers in Go

Sorting a slice of integers in Go

Last updated: November 21, 2024

Understanding Sorting in Go

Sorting is a fundamental task in computer science and software development. When working with Go, sorting a slice of integers is straightforward and involves using the sort package available in the Go standard library. In this article, we'll explore how to sort a slice of integers from basic to advanced examples.

Basic Sorting with sort.Ints

Let's start by sorting a simple slice of integers in ascending order using sort.Ints.

package main

import (
    "fmt"
    "sort"
)

func main() {
    nums := []int{4, 2, 7, 1, 9}
    sort.Ints(nums)
    fmt.Println("Sorted slice:", nums)
}

In this example, sort.Ints takes the slice of integers nums and sorts them in ascending order.

Intermediate Sorting: Sorting in Descending Order

To sort a slice in descending order, we need a more customized approach. We can use sort.Sort and implement the sort.Interface interface.

package main

import (
    "fmt"
    "sort"
)

type ByDescending []int

func (a ByDescending) Len() int           { return len(a) }
func (a ByDescending) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByDescending) Less(i, j int) bool { return a[i] > a[j] }

func main() {
    nums := []int{4, 2, 7, 1, 9}
    sort.Sort(ByDescending(nums))
    fmt.Println("Sorted slice in descending order:", nums)
}

Here, by implementing sort.Interface, we create a custom sorting logic that rearranges the slice in descending order.

Advanced Sorting: Custom Comparison and Stability

In some scenarios, stability in sorting where duplicates retain their relative order, might be required. For this, use sort.SliceStable.

package main

import (
    "fmt"
    "sort"
)

func main() {
    nums := []int{4, 2, 7, 7, 1, 9}
    sort.SliceStable(nums, func(i, j int) bool {
        return nums[i] < nums[j] // Stable ascending sort
    })
    fmt.Println("Stable sorted slice:", nums)
}

sort.SliceStable allows more complex sorting criteria with the added benefit of stability, maintaining the order of equivalent elements.

Using these techniques, you can efficiently handle sorting in different scenarios using the Go programming language. From simple to custom and more complex needs, Go's sort package provides the tools required for efficient integer sorting.

Next Article: Sorting a slice of floats in Go

Previous Article: How to remove duplicates from a slice in Go

Series: Working with Slices in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant