-
Notifications
You must be signed in to change notification settings - Fork 86
/
sorting.go
84 lines (70 loc) · 1.99 KB
/
sorting.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"sort"
)
type person struct {
Name string
Age int
}
type byNameLength []person
// Len is a method needed to implements Interface interface
// represent the slice length
func (s byNameLength) Len() int {
return len(s)
}
// Swap is a method needed to implements Interface interface
// how elements changes your position
func (s byNameLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Less is a method needed to implements Interface interface
// compare method used in sort method
func (s byNameLength) Less(i, j int) bool {
return len(s[i].Name) < len(s[j].Name)
}
func main() {
// order strings
strs := []string{"Felipe", "Cássio", "Gustavo", "César"}
sort.Strings(strs)
fmt.Println("Ordered slice: ", strs)
// order ints
ints := []int{7, 2, 5, 1, 4, 8, 6, 3}
sort.Ints(ints)
fmt.Println("Ordered slice: ", ints)
// verify if slice is sorted
fmt.Printf("Are sorted? %t\n", sort.IntsAreSorted(ints))
// important notes
// slice have to be sorted
// always verify if returned position is lower than length of slice
// and the number of that position is equal the searched number
x := 4
// binary search
c := sort.Search(len(ints), func(i int) bool { return ints[i] >= x })
if x < len(ints) && ints[c] == x {
fmt.Printf("found %d at index %d in %v\n", x, c, ints)
} else {
fmt.Printf("%d not found in %v\n", x, ints)
}
// or
// The slice must be sorted in ascending order
// The return value is the index to insert x if x is not present (it could be len(a)).
i := sort.SearchInts(ints, x)
if x < len(ints) && ints[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, c, ints)
} else {
fmt.Printf("%d not found in %v\n", x, ints)
}
people := []person{
{"Mari", 24},
{"Venilton", 60},
{"Cassio", 26},
}
// sorting persons by name length
sort.Sort(byNameLength(people))
fmt.Println(people)
// Interesting links
// - https://gobyexample.com/sorting
// - https://gobyexample.com/sorting-by-functions
// - https://golang.org/pkg/sort/
}