-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-common-functions.go
54 lines (41 loc) · 1.16 KB
/
4-common-functions.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
// Sorting
// Custom Sorting
package main
import (
"fmt"
"sort"
)
func commonFunctions() {
// Sorting
/*
Sorting of built in types
Sorting is in place, so it changes the given slice and doesnt return a new one
*/
strs := []string{"c", "a", "b"}
sort.Strings(strs)
fmt.Println("Strings:", strs) // Prints Strings: [a b c]
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println("Ints:", ints) // Prints Ints: [2 4 7]
a := sort.IntsAreSorted(ints)
fmt.Println("Sorted:", a) // Prints Sorted: true. Check if a slice is already in sorted order.
/*
Custom sorting
*/
fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(byLength(fruits)) // Convert fruits slice to byLength, then use sort.Sort on that typed slice
fmt.Println(fruits) // Prints [kiwi peach banana]
}
type byLength []string
/*
Implement sort.Interface - Len, Less, and Swap - on the byLength type so we can use the sort packages generic Sort function.
*/
func (b byLength) Len() int {
return len(b)
}
func (b byLength) Swap(c, d int) {
b[c], b[d] = b[d], b[c]
}
func (b byLength) Less(c, d int) bool {
return len(b[c]) < len(b[d]) // sort in order of increasing length
}