github.com/gopherd/gonum@v0.0.4/graph/internal/ordered/sort.go (about) 1 // Copyright ©2015 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package ordered 6 7 import ( 8 "sort" 9 10 "github.com/gopherd/gonum/graph" 11 ) 12 13 // ByID sorts a slice of graph.Node by ID. 14 func ByID(n []graph.Node) { 15 sort.Slice(n, func(i, j int) bool { return n[i].ID() < n[j].ID() }) 16 } 17 18 // BySliceValues sorts a slice of []int64 lexically by the values of the 19 // []int64. 20 func BySliceValues(c [][]int64) { 21 sort.Slice(c, func(i, j int) bool { 22 a, b := c[i], c[j] 23 l := len(a) 24 if len(b) < l { 25 l = len(b) 26 } 27 for k, v := range a[:l] { 28 if v < b[k] { 29 return true 30 } 31 if v > b[k] { 32 return false 33 } 34 } 35 return len(a) < len(b) 36 }) 37 } 38 39 // BySliceIDs sorts a slice of []graph.Node lexically by the IDs of the 40 // []graph.Node. 41 func BySliceIDs(c [][]graph.Node) { 42 sort.Slice(c, func(i, j int) bool { 43 a, b := c[i], c[j] 44 l := len(a) 45 if len(b) < l { 46 l = len(b) 47 } 48 for k, v := range a[:l] { 49 if v.ID() < b[k].ID() { 50 return true 51 } 52 if v.ID() > b[k].ID() { 53 return false 54 } 55 } 56 return len(a) < len(b) 57 }) 58 } 59 60 // Int64s sorts a slice of int64. 61 func Int64s(s []int64) { 62 sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) 63 } 64 65 // LinesByIDs sort a slice of graph.LinesByIDs lexically by the From IDs, 66 // then by the To IDs, finally by the Line IDs. 67 func LinesByIDs(n []graph.Line) { 68 sort.Slice(n, func(i, j int) bool { 69 a, b := n[i], n[j] 70 if a.From().ID() != b.From().ID() { 71 return a.From().ID() < b.From().ID() 72 } 73 if a.To().ID() != b.To().ID() { 74 return a.To().ID() < b.To().ID() 75 } 76 return n[i].ID() < n[j].ID() 77 }) 78 } 79 80 // Reverse reverses the order of nodes. 81 func Reverse(nodes []graph.Node) { 82 for i, j := 0, len(nodes)-1; i < j; i, j = i+1, j-1 { 83 nodes[i], nodes[j] = nodes[j], nodes[i] 84 } 85 }