Sort slice of struct based order by number and alphabetically

fzlrhmn :

I have a slice of struct like this

type Interval struct{
    number     float64
    coordinate string
}

var data []Interval

assume the data is like below

[]Interval{
    Interval{
        number: 1,
        coordinate: "x",
    },
    Interval{
        number: 8,
        coordinate: "y",
    },
    Interval{
        number: 2,
        coordinate: "x",
    },
    Interval{
        number: 5,
        coordinate: "y",
    },
    Interval{
        number: 5,
        coordinate: "x",
    },
    Interval{
        number: 6,
        coordinate: "y",
    },
    Interval{
        number: 3,
        coordinate: "x",
    },
    Interval{
        number: 7,
        coordinate: "y",
    },
}

My question is how can I sort this by number and coordinate?

I have tried with below sort method, but it is not as my expectation

// sort method that I use
sort.Slice(data, func(i, j int) bool {
    return data[i].number < data[j].number
})

result:

[{1 x} {2 x} {3 x} {5 y} {5 x} {6 y} {7 y} {8 y}]

expectation:

[{1 x} {2 x} {3 x} {5 x} {5 y} {6 y} {7 y} {8 y}]

diff: {5 y} {5 x} should be {5 x} {5 y}

hints: My expectation result is similar with what python has with function sort

really appreciate with any help

hqt :

Your comparator function doesn't compare property coordinate in the situation property number is equal. Hence the position of {5, x} and {5, y} might be non-deterministic if the sorting algorithm is not stable.

Here is the updated version of the comparator function:

sort.Slice(data, func(i, j int) bool {
    if data[i].number != data[j].number {
        return data[i].number < data[j].number
    }
    return data[i].coordinate < data[j].coordinate
})

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405151&siteId=1