我有什么:“计算机科学蒸馏”书中伪码中的算法(第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)
}输出为[5 2 7 9]。我是不是遗漏了什么?
发布于 2020-04-03 07:36:59
我不知道Go,但googling确认Go有零基编号。在您的示例中,您从1开始(应该是0)。
另一件事--你为什么需要current_tmp和smallest_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)
}https://stackoverflow.com/questions/61006937
复制相似问题