首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从“计算机科学分册”看排序算法

从“计算机科学分册”看排序算法
EN

Stack Overflow用户
提问于 2020-04-03 07:25:42
回答 1查看 37关注 0票数 0

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

代码语言:javascript
复制
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中写道:

代码语言:javascript
复制
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)
}

游乐场

输出为[5 2 7 9]。我是不是遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-03 07:36:59

我不知道Go,但googling确认Go有零基编号。在您的示例中,您从1开始(应该是0)。

另一件事--你为什么需要current_tmpsmallest_tmp

因此,我建议如下:

代码语言:javascript
复制
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)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61006937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档