了解《计算机科学蒸馏》一书中的排序算法

时间:2020-04-03 07:25:42

标签: algorithm sorting

我拥有什么:“计算机科学蒸馏”一书中的伪代码算法(第27页)

function selection_sort(list)
    for current <- 1 ... list.length - 1
        smallest <- current
        for i <- current + 1 ... list.length
            if list[i] < list[smallest]
                smallest <- i
        list.swap_items(current, smallest)

我试图理解它,所以我用Go语言编写了它:

func main() {
    list := []int{5, 2, 7, 9}
    for current := 1; current < len(list)-1; current++ {
        smallest := current
        for i := current + 1; i < len(list); i++ {
            if list[i] < list[smallest] {
                smallest = i
            }
        }
        current_tmp := list[current]
        smallest_tmp := list[smallest]
        list[current], list[smallest] = smallest_tmp, current_tmp
    }
    fmt.Printf("%v\n", list)
}

Playground

输出为[5 2 7 9]。 我想念什么吗?

1 个答案:

答案 0 :(得分:1)

我不知道Go,但是谷歌搜索确认Go具有从零开始的编号。 在您的示例中,您从1(应为0)开始。

另一件事-为什么需要current_tmpsmallest_tmp

所以我建议以下内容:

func main() {
    list := []int{5, 2, 7, 9}
    for current := 0; current < len(list)-1; current++ {
        smallest := current
        for i := current + 1; i < len(list); i++ {
            if list[i] < list[smallest] {
                smallest = i
            }
        }
        list[current], list[smallest] = list[smallest], list[current]
    }
    fmt.Printf("%v\n", list)
}