Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a slice in go without mutating the original slice

Tags:

go

In Golang, I am trying to sort a slice without mutating the original value

func main() {
    originalArray := []int{4, 2, 1, 1, 2}
    newArray := originalArray
    sort.Ints(newArray)

    fmt.Printf("%v", originalArray) // prints [1 1 2 2 4]
}

How can I sort a slice in golang without mutating the original value?

like image 411
Kevin Amiranoff Avatar asked Oct 15 '25 02:10

Kevin Amiranoff


2 Answers

You need to make a copy of the original slice.

Use:

newArray := make([]int, len(originalArray))
copy(newArray, originalArray)

or:

newArray := append([]int{}, originalArray...)
like image 188
leaf bebop Avatar answered Oct 17 '25 16:10

leaf bebop


The general way is:

s2 := slices.Clone(s)
// sort s2 as needed, s won't be affected

This always works but requires a clone of the slice. If the slice elements are large and the slice is long it can require allocating (at least temporarily) large amounts of memory. In this case you could allocate a slice of indexes, and sort that instead.

si := make([]int, len(s))
for i := range si {
  si[i] = i
}
sort.Slice(si, func(i, j) int {
  ei, ej := s[si[i]], s[si[j]]
  return ... // compare ei and ej
})
// to access the i-th sorted element, use s[si[i]]
// the order of s is unaffected
like image 20
CAFxX Avatar answered Oct 17 '25 16:10

CAFxX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!