1

我正在实现排序,但在 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”行中遇到错误,表示恐慌:运行时错误:索引超出范围

    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
 }

但我不认为交换是问题。

4

1 回答 1

1

你有一个错字:

for j := first_index; i < last_index; j++ {

应该:

for j := first_index; j < last_index; j++ {

容易犯的错误:-)

游乐场示例

于 2013-08-31T07:08:23.883 回答