diff --git a/eBook/exercises/chapter_11/min_interface.go b/eBook/exercises/chapter_11/min_interface.go index eabfe31a5..52a3891d6 100755 --- a/eBook/exercises/chapter_11/min_interface.go +++ b/eBook/exercises/chapter_11/min_interface.go @@ -5,16 +5,19 @@ type Miner interface { Len() int ElemIx(ix int) interface{} Less(i, j int) bool + Swap(i, j int) } func Min(data Miner) interface{} { - j := 0 + min := data.ElemIx(0) for i := 1; i < data.Len(); i++ { - if data.Less(i, j) { - j = i + if data.Less(i, i-1) { + min = data.ElemIx(i) + } else { + data.Swap(i, i-1) } } - return data.ElemIx(j) + return min } type IntArray []int @@ -22,9 +25,11 @@ type IntArray []int func (p IntArray) Len() int { return len(p) } func (p IntArray) ElemIx(ix int) interface{} { return p[ix] } func (p IntArray) Less(i, j int) bool { return p[i] < p[j] } +func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } type StringArray []string func (p StringArray) Len() int { return len(p) } func (p StringArray) ElemIx(ix int) interface{} { return p[ix] } func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } +func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }