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?
You need to make a copy of the original slice.
Use:
newArray := make([]int, len(originalArray))
copy(newArray, originalArray)
or:
newArray := append([]int{}, originalArray...)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With