From 80b74f6d08a6a6fa6bc757ff378b87b60cab3f7a Mon Sep 17 00:00:00 2001 From: crackedcd Date: Mon, 10 Sep 2018 18:34:37 +0800 Subject: [PATCH] Update min_interface.go (#543) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Min(data Miner) 方法存在bug,原因是: 该方法的逻辑类似冒泡排序, 将Miner类型变量的集合挨个两两比对,但方法中仅将两变量的较小值取出(Less()方法),并赋值记录为min,最后返回,并没有进行“冒泡”这个swap操作。 因此补充了Swap()相关的接口和实现定义,并补充了Swap()在Min()方法中的逻辑。 --- eBook/exercises/chapter_11/min_interface.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/eBook/exercises/chapter_11/min_interface.go b/eBook/exercises/chapter_11/min_interface.go index eabfe31..52a3891 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] }