21
golang排序二维切片
source link: https://studygolang.com/articles/30460
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
排序二维切片,思路算是比较明确,但是中间由于某些细节没有处理好,导致调试了很久才写出正确的版本。
type tds [][]string func (d tds) Len() int { return len(d) } func (d tds) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d tds) Less(i, j int) bool { n := len(d[i]) for k := 0; k < n; k++ { if d[i][k] < d[j][k] { return true } else if d[i][k] == d[j][k] { continue } else { return false } } return false } func main() { fmt.Println("hello world") fmt.Println("dd" < "ab") t := [][]string{ {"ba", "ab", "bc"}, {"ab", "bc", "bb"}, {"dd", "ac", "ab"}, } sort.Sort(tds(t)) fmt.Println(t) }
出现失误的地方在于 Swap
函数中的 for
循环,一开始写的版本如下
func (d dts) Less(i, j int) bool { n := len(d[i]) for k := 0; k < n; k++ { if d[i][k] < d[j][k] { return true } } return false }
代码中的逻辑为,如果 d[i][k] < d[j][k]
就返回 true
,否则继续进行比较。咋一看没啥问题,然而这确实一个bug。这样的逻辑会将 ["bb", "aa"]
和 ["aa", "bb"]
的Less操作返回 true
,而实际在检测到 "bb" > "aa"
时就应该返回 false
,而在错误的代码逻辑中没有返回,而是继续比较第二项 “aa”
和 bb
,所以会返回错误的结果。
有疑问加站长微信联系
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK