package main
import (
"fmt"
"sort"
)
func main() {
x := make([]int, 5)
x[4] = 1
x[0] = 5
sort.Slice(x, func(i, j int) bool {
return i < j
})
fmt.Println(x)
}
I want the above code to print [0 0 0 1 5]. But it prints [5 0 0 0 1]. Am I misusing this function? Or what am I doing wrong?
>Solution :
The reason why your code is showing this is because, i and j are NOT the elements of your slice. i and j are the INDEX of your slice. Thus, your correct code should be
instead of:
return i < j
The correct answer is:
return x[i] < x[j]