github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/sort/subsort/02-int.go (about) 1 package subsort 2 3 import "sort" 4 5 type SortedByIntVal struct { 6 IdxOrig int // index of the original slice 7 Val int // dynamically filled value to be sorted by 8 } 9 10 type sliceSortableIntAsc []SortedByIntVal 11 type sliceSortableIntDesc []SortedByIntVal 12 13 func (s sliceSortableIntAsc) Len() int { 14 return len(s) 15 } 16 17 func (s sliceSortableIntAsc) Swap(i, j int) { 18 s[i], s[j] = s[j], s[i] 19 } 20 21 func (s sliceSortableIntAsc) Less(i, j int) bool { 22 if s[i].Val < s[j].Val { 23 return true 24 } 25 return false 26 } 27 func (s sliceSortableIntDesc) Len() int { 28 return len(s) 29 } 30 31 func (s sliceSortableIntDesc) Swap(i, j int) { 32 s[i], s[j] = s[j], s[i] 33 } 34 35 func (s sliceSortableIntDesc) Less(i, j int) bool { 36 if s[i].Val > s[j].Val { 37 return true 38 } 39 return false 40 } 41 42 // 43 // A second way only requires the callee 44 // only to submit a func, that extracts the sort value by index: 45 type ExtractIntFielder func(i int) int 46 47 // 48 // An interface ExtractIntFielder, would require all callee slices to be wrapped. 49 func SortByIntValAsc(size int, f ExtractIntFielder) []SortedByIntVal { 50 51 copyOfSubset := make([]SortedByIntVal, size) 52 for i := 0; i < size; i++ { 53 copyOfSubset[i].IdxOrig = i 54 copyOfSubset[i].Val = f(i) 55 } 56 57 wrapperSortable := sliceSortableIntAsc(copyOfSubset) 58 sort.Sort(wrapperSortable) 59 unwrap := []SortedByIntVal(wrapperSortable) 60 return unwrap 61 62 } 63 func SortByIntValDesc(size int, f ExtractIntFielder) []SortedByIntVal { 64 65 copyOfSubset := make([]SortedByIntVal, size) 66 for i := 0; i < size; i++ { 67 copyOfSubset[i].IdxOrig = i 68 copyOfSubset[i].Val = f(i) 69 } 70 71 wrapperSortable := sliceSortableIntDesc(copyOfSubset) 72 sort.Sort(wrapperSortable) 73 unwrap := []SortedByIntVal(wrapperSortable) 74 return unwrap 75 76 }