How to sort a slice stable in Golang?


When sorting slices of data in Go, sometimes it's important to maintain the original order of elements that have the same sort key. This is where stable sorting comes into play. A stable sort algorithm ensures that the order of elements with the same sort key remains the same after sorting. Go provides a built-in sort package that includes a stable sorting algorithm. In this article, we will discuss how to sort a slice stably in Go.

The sort package in Go provides two functions for sorting slices: sort.Slice() and sort.SliceStable(). The sort.Slice() function sorts a slice of values based on a less function that defines the sort order. On the other hand, sort.SliceStable() sorts a slice of values based on a less function that defines the sort order and maintains the original order of elements with the same sort key.

Example

Here's an example of how to sort a slice of integers stably using sort.SliceStable() −

package main

import (
   "fmt"
   "sort"
)

func main() {
   nums := []int{5, 2, 8, 2, 9, 3}
   fmt.Println("Original slice:", nums)
   
   sort.SliceStable(nums, func(i, j int) bool {
      return nums[i] < nums[j]
   })
   
   fmt.Println("Sorted slice:", nums)
}

Output

Original slice: [5 2 8 2 9 3]
Sorted slice: [2 2 3 5 8 9]

In the above example, we create a slice of integers and print out the original slice. We then sort the slice stably in ascending order using the sort.SliceStable() function and a custom less function that compares the i-th and j-th elements of the slice.

Example

Here's another example of how to sort a slice of string values stably using sort.SliceStable() −

package main

import (
   "fmt"
   "sort"
)

func main() {
   names := []string{"Alice", "Bob", "Charlie", "David", "Bob", "Charlie"}
   fmt.Println("Original slice:", names)

   sort.SliceStable(names, func(i, j int) bool {
      return names[i] < names[j]
   })

   fmt.Println("Sorted slice:", names)
}

Output

Original slice: [Alice Bob Charlie David Bob Charlie]
Sorted slice: [Alice Bob Bob Charlie Charlie David]

In the above example, we create a slice of string values and print out the original slice. We then sort the slice stably in ascending order using the sort.SliceStable() function and a custom less function that compares the i-th and j-th elements of the slice.

Conclusion

Sorting slices stably is important when you need to maintain the original order of elements with the same sort key. Go provides a built-in sort package that includes a stable sorting algorithm. By using the sort.SliceStable() function and a custom less function, you can sort a slice stably in Go.

Updated on: 25-Apr-2023

675 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements