Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go: sort.slice is sorting incorrectly

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading