Last active
January 31, 2022 11:53
-
-
Save callerobertsson/0619f6cc9bbcdb598e5d1bac84a9922f to your computer and use it in GitHub Desktop.
Golang: Stable sort on priority and order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
// Item has a priority and an order | |
type Item struct { | |
Prio int | |
Order int | |
} | |
// ByPrio is a slice of Item which implements the sort.Interface | |
type ByPrio []Item | |
// Len is i the sort.Interface | |
func (b ByPrio) Len() int { | |
return len(b) | |
} | |
// Less is in the sort.Interface | |
func (b ByPrio) Less(i, j int) bool { | |
// Higher prio comes first | |
return b[i].Prio > b[j].Prio | |
} | |
// Swap is in the sort.Interface | |
func (b ByPrio) Swap(i, j int) { | |
b[i], b[j] = b[j], b[i] | |
} | |
// Example | |
func main() { | |
items := generateItems(10) | |
fmt.Printf("\n Unordered Items\n\n%v\n", stringify(items)) | |
sort.Stable(ByPrio(items)) | |
fmt.Printf(" Ordered Items\n\n%v\n", stringify(items)) | |
} | |
func stringify(is []Item) (s string) { | |
s += fmt.Sprintf(" Index | Order | Prio\n") | |
s += fmt.Sprintf("-------+-------+------\n") | |
for c, i := range is { | |
s += fmt.Sprintf("%6d |%6d |%5d\n", c, i.Order, i.Prio) | |
} | |
return s | |
} | |
func generateItems(n int) []Item { | |
ii := []Item{} | |
for order := 0; order < n; order++ { | |
prio := 0 | |
if order%3 == 0 { | |
prio = 1 + order | |
} | |
ii = append(ii, Item{prio, order}) | |
} | |
return ii | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment