【问题标题】:Out of Bounds of an Array [Bubble Selection with ArrayList]数组越界 [使用 ArrayList 进行气泡选择]
【发布时间】:2014-01-29 04:06:43
【问题描述】:

我正在编写一个气泡选择方法,它应该与这些凭据一起使用:

/* Write code for a Bubble Sort algorithm that starts at the right side of
 * of ArrayList of Comparable objects and "bubbles" the largest item to the
 * left of the list.  The result should be an ArrayList arranged in descending
 * order.
 */
 @SuppressWarnings("unchecked") 
 void bubbleSort(ArrayList <Comparable> list) {

    int end = list.size();

    for (int i = 0 ; i < end; i++){
        for (int j = end; j > 0; j--){
            if ( list.get(j).compareTo(list.get(j-1)) > 0 ){
                //swap
                Comparable temp = list.get(j);
                list.set(j,list.get(j - 1));
                list.set(j - 1, temp);
                //System.out.println(list);
            }
        }   
        end--;
    }
}

问题是,Java 会告诉我它超出了范围。

如果我改为使用

for (int j = end - 1; j > 0; j--)

然后代码将运行,但它不会运行列表完全完成排序所需的运行次数(也就是它提前停止一个循环)

【问题讨论】:

  • 在内部循环中,您有 N 个对象,并且您希望将每个对象与前一个对象进行比较以在需要时交换它们,因此您必须进行 N-1 个检查,因为第一个对象没有前一个对象. for (int j = end - 1; j &gt; 0; j--) 是对的。

标签: java sorting arraylist indexoutofboundsexception


【解决方案1】:

使用此代码将满足您在数组实现中的要求,其中 size 是您的数组长度。

for (int i = 0; i < size - 1; j++) {
    for (int j = i + 1; j < size - 1; k++){
        if (array[i] > array[j]) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp; 
        }   
    }
}

【讨论】:

    【解决方案2】:

    如果数组是 long 3,则 array[3] 越界。 由于您从 array[lenght] 开始,因此您必须在进入 for 循环之前将其递减,就像您提供的代码一样。

    【讨论】:

      【解决方案3】:

      如上所述,您需要从 end-1 开始,否则您将访问数组边界之外的内容。


      假设您有一个整数数组:5 1 4

      你的算法会这样做:

      第一次迭代 -> i = 0 / j 从 2 开始

      1 5 4
      

      第二次迭代 -> i = 1 / j 从 1 开始

      它现在只会比较 5 和 1 而不会切换它们,因为 5 更高。那么,4和5呢?他们应该被交换。你的算法实现是错误的。

      如果您删除end--;,它应该可以工作。 但是,这可以优化

      【讨论】:

      • 你是对的,你使用的是 j-1,所以它会尝试搜索索引 -1。我的错。
      【解决方案4】:

      使用end - 1 将比较列表中的倒数第二个值 如果您使用end,它将尝试比较最后一个值和索引处的值,这将给出ArrayOutOfBound Exception

      现在要正确输出,您必须删除 end--; 行,如下所示

      for (int i = 0 ; i < end; i++){
              for (int j = end -1; j > 0; j--){
                  if ( list.get(j).compareTo(list.get(j-1)) > 0 ){
                      //swap
                      Comparable temp = list.get(j);
                      list.set(j,list.get(j - 1));
                      list.set(j - 1, temp);
                  }
              } 
              //remove below line
              end--;
          }
      

      这也会将列表从右侧缩短一个值。所以删除这将起作用

      【讨论】:

        猜你喜欢
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多