Go:数组超出索引恐慌错误

时间:2013-08-31 06:30:30

标签: arrays sorting indexing go

我正在实现排序,但继续使用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]&lt; = 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
 }

但我不认为交换是问题。

1 个答案:

答案 0 :(得分:1)

你有一个错字:

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

应该是:

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

很容易犯错: - )

Playground example