How do I sort slice of pointer to a struct. I am trying to sort the slice based on the start time.
/**
* Definition for an Interval.
* type Interval struct {
* Start int
* End int
* }
*/
func employeeFreeTime(schedule [][]*Interval) []*Interval {
fmt.Println("Schedule initial #", schedule)
sort.Slice(schedule, func(i,j int) bool{
return schedule[i].Start < schedule[j].Start
})
fmt.Println(schedule)
return nil
}
Send in a slice, instead of a slice of slices and you can sort just fine:
/**
* Definition for an Interval.
*/
type Interval struct {
Start int
End int
}
func employeeFreeTime(schedule []*Interval) []*Interval {
fmt.Println("Schedule initial #", schedule)
sort.Slice(schedule, func(i,j int) bool{
return schedule[i].Start < schedule[j].Start
})
fmt.Println(schedule)
return nil
}
func main() {
intervals := []*Interval {
{
Start: 10,
End: 100,
},
{
Start: 5,
End: 100,
},
}
employeeFreeTime(intervals)
}
In case you want to sort all the Interval
s among the slice of slice.
func employeeFreeTime(schedule [][]*Interval) []*Interval {
var tempSlice []*Interval
for _, slice := range schedule {
tempSlice = append(tempSlice, slice...)
}
sort.Slice(tempSlice, func(i, j int) bool {
return tempSlice[i].Start < tempSlice[j].Start
})
return tempSlice
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.