-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathselection.go
40 lines (33 loc) · 926 Bytes
/
selection.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
package sorting
// Selection Sort
// First, find the smallest item int the slice, and swap it with the first entry
// Then, find the next smallest item and swap it with the second entry
// Continue in this way until the entire slice is sorted
// This method is called selection sort because it works by repeatedly selecting
// the smallest remaining items
func SelectionSort(x Sortable) {
n := x.Len()
for i := 0; i < n; i++ {
ithMin := i // the i-th smallest item's index
for j := i + 1; j < n; j++ {
if x.Less(j, ithMin) {
ithMin = j
}
}
x.Swap(i, ithMin)
}
}
type Selection struct{}
func NewSelection() Sorter {
return Selection{}
}
// Implements Sorter
func (s Selection) SortInts(x []int) {
SelectionSort(IntSortSlice(x))
}
func (s Selection) SortFloat64s(x []float64) {
SelectionSort(Float64SortSlice(x))
}
func (s Selection) SortStrings(x []string) {
SelectionSort(StringSortSlice(x))
}