英文:
Go: array out of index panic error
问题
我正在实现排序算法,但在Go语言中一直遇到索引越界错误。
我的代码如下:
func My_Partition(container []int, first_index int, last_index int) int {
var x int = container[last_index]
i := first_index - 1
for j := first_index; i < last_index; j++ {
if container[j] <= x {
i += 1
my_Swap(&container[i], &container[j])
}
}
my_Swap(&container[i+1], &container[last_index])
return i+1
}
我在第 "if container[j] <= x" 这一行遇到错误,错误信息是 "panic: runtime error: index out of range"
main.My_Partition(0x2101b20c0, 0x7, 0x7, 0x0, 0x6, ...)
/Path/main.go:34 +0xff
有人有什么想法吗?
我的交换函数如下:
func my_Swap(a *int, b *int) {
temp := *a
*a = *b
*b = temp
}
但我不认为交换函数是问题所在。
英文:
I am implementing sorting but keep getting the index bound error in Go language.
My code is following
func My_Partition(container []int, first_index int, last_index int) int {
var x int = container[last_index]
i := first_index - 1
for j := first_index; i < last_index; j++ {
if container[j] <= x {
i += 1
my_Swap(&container[i], &container[j])
}
}
my_Swap(&container[i+1], &container[last_index])
return i+1
}
I am getting error in the line "if container[j] <= x" that says panic: runtime error: index out of range
main.My_Partition(0x2101b20c0, 0x7, 0x7, 0x0, 0x6, ...)
/Path/main.go:34 +0xff
Anybody has an idea?
my swap function is below
func my_Swap(a *int, b *int) {
temp := *a
*a = *b
*b = temp
}
but I don't think swap is the problem.
答案1
得分: 1
你有一个拼写错误:
for j := first_index; i < last_index; j++ {
应该是:
for j := first_index; j < last_index; j++ {
这是一个很容易犯的错误
英文:
You have a typo:
for j := first_index; i < last_index; j++ {
Should be:
for j := first_index; j < last_index; j++ {
Easy enough mistake to make
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论