Skip to content

Commit

Permalink
Update min_interface.go (unknwon#543)
Browse files Browse the repository at this point in the history
Min(data Miner) 方法存在bug,原因是: 该方法的逻辑类似冒泡排序, 将Miner类型变量的集合挨个两两比对,但方法中仅将两变量的较小值取出(Less()方法),并赋值记录为min,最后返回,并没有进行“冒泡”这个swap操作。
因此补充了Swap()相关的接口和实现定义,并补充了Swap()在Min()方法中的逻辑。
  • Loading branch information
crackedcd authored and unknwon committed Sep 10, 2018
1 parent c28a3f0 commit 80b74f6
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions eBook/exercises/chapter_11/min_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,31 @@ 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

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] }

0 comments on commit 80b74f6

Please sign in to comment.