知识卡片

结构图卡 · 470.b.1.a.1.c.3.a.6.a.3.a.1.c.5.e

排序契约分离算法与表示

理解等级:中级

sort.Interface只要求Len、Less、Swap,通用算法不需要知道元素结构。StringSlice(names)转换后仍共享原底层数组,Swap会改变原顺序,不是得到独立副本。Track指针可减少交换时复制的体积,但整体快慢仍受间接访问等成本影响,不能只凭指针较小就断言总会更快。

结构图: 类图

classDiagram
 class Interface {
 <<interface>>
 Len() int
 Less(i, j int) bool
 Swap(i, j int)
 }
 class StringSlice {
 <<definedSlice>>
 Len() int
 Less(i, j int) bool
 Swap(i, j int)
 }
 Interface <|.. StringSlice : 满足排序契约
这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • · 查看原书依据

      type Interface interface { Len() int Less(i, j int) bool // i, j are indices of sequence elements Swap(i, j int) }

    参考来源

    - 位置:《Go语言圣经》第07章《sort.Interface接口》(来源项目book-sources:extracted/Go语言圣经/_epub-src/ch7-06.html;spine 63,归一字符[465,579)) - 结论依据:三个方法和共享切片转换支持算法与表示解耦,正文限定性能结论。 - 原始内容:type Interface interface { Len() int Less(i, j int) bool // i, j are indices of sequence elements Swap(i, j int) }