mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 19:22:37 +08:00
Min(data Miner) 方法存在bug,原因是: 该方法的逻辑类似冒泡排序, 将Miner类型变量的集合挨个两两比对,但方法中仅将两变量的较小值取出(Less()方法),并赋值记录为min,最后返回,并没有进行“冒泡”这个swap操作。 因此补充了Swap()相关的接口和实现定义,并补充了Swap()在Min()方法中的逻辑。
36 lines
925 B
Go
Executable File
36 lines
925 B
Go
Executable File
// min_interface.go
|
|
package min
|
|
|
|
type Miner interface {
|
|
Len() int
|
|
ElemIx(ix int) interface{}
|
|
Less(i, j int) bool
|
|
Swap(i, j int)
|
|
}
|
|
|
|
func Min(data Miner) interface{} {
|
|
min := data.ElemIx(0)
|
|
for i := 1; i < data.Len(); i++ {
|
|
if data.Less(i, i-1) {
|
|
min = data.ElemIx(i)
|
|
} else {
|
|
data.Swap(i, i-1)
|
|
}
|
|
}
|
|
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] }
|