mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 22:06:51 +08:00
Update min_interface.go (#543)
Min(data Miner) 方法存在bug,原因是: 该方法的逻辑类似冒泡排序, 将Miner类型变量的集合挨个两两比对,但方法中仅将两变量的较小值取出(Less()方法),并赋值记录为min,最后返回,并没有进行“冒泡”这个swap操作。 因此补充了Swap()相关的接口和实现定义,并补充了Swap()在Min()方法中的逻辑。
This commit is contained in:
@@ -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] }
|
||||
|
Reference in New Issue
Block a user