英文:
Quicksort in Go
问题
我正在学习Go,并尝试实现快速排序算法,但是它没有返回完整的列表。根据我对Go的理解,它与我编写的一个正常工作的Ruby实现相匹配。
我的代码如下:
func quickSort(data []string) []string {
if len(data) > 1 {
pivot := data[0]
smaller := make([]string, 0, len(data))
equal := make([]string, 0, len(data))
larger := make([]string, 0, len(data))
for i := 1; i < len(data); i++ {
if data[i] > pivot {
larger = append(larger, data[i])
} else if data[i] < pivot {
smaller = append(smaller, data[i])
} else {
equal = append(equal, data[i])
}
}
return append(append(quickSort(smaller), equal...), quickSort(larger)...)
} else {
return data
}
}
我对其中的问题感到非常困惑。
英文:
I'm learning Go, and tried to implement a quicksort, however it doesn't return a complete list. To my understanding of Go it matches with a functioning Ruby implementation I wrote.
My code is:
func quickSort(data []string) []string {
if len(data) > 1 {
pivot := data[0]
smaller := make([]string, 0, len(data))
equal := make([]string, 0, len(data))
larger := make([]string, 0, len(data))
for i := 1; i < len(data); i++ {
if data[i] > pivot {
larger = append(larger, data[i])
} else if data[i] < pivot {
smaller = append(smaller, data[i])
} else {
equal = append(equal, data[i])
}
}
return append(append(quickSort(smaller), equal...), quickSort(larger)...)
} else {
return data
}
}
I am very puzzled as to what in this doesn't work.
答案1
得分: 6
你的问题是你从未将枢轴值附加到返回的切片中。因此,在每次递归调用中,你都会丢失枢轴。
对代码进行以下更改,它就会正常工作:
equal := make([]string, 1, len(data))
equal[0] = pivot
英文:
The bug you have is that you never append the pivot value to the returned slice. So for each recursive call, you will lose the pivot.
Make the following change to the code and it will work:
equal := make([]string, 1, len(data))
equal[0] = pivot
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论