【问题标题】:QuickSort IndexOutOfBound exception arraylistQuickSort IndexOutOfBound 异常数组列表
【发布时间】:2019-03-09 21:07:48
【问题描述】:

您好,我正在尝试编写 QuickSort 代码,但是我总是遇到超出范围的索引? 我的代码如下:

public class QuickSort
{
    public void quickSort(ArrayList<Integer> A, int p, int r)
    {
        if (p < r) {
            int q = partition(A, p, r);
            quickSort(A, p, q - 1);
            quickSort(A, q + 1, r);
        }
    }
    public int partition(ArrayList<Integer> A, int p, int r) {
        int x = A.get(r);
        int i = p - 1;
        for (int j = p ; j < r; j++) {
            if (A.get(j) <= x) {
                i++;
                Collections.swap(A, A.get(i), A.get(j));
            }
        }
        Collections.swap(A, A.get(i + 1), A.get(r));
        return (i + 1);
    }
}

我用的是书中的代码:《算法导论》

我正在尝试快速排序ArrayListA

public class TestDriver
{
    public static void testQuick() {
        //Laver et random array A
        ArrayList<Integer> A = new ArrayList<>();
        for (int i = 1; i <12; i++) {
            A.add(i);
        }
        Collections.shuffle(A);
        int n = A.size();
        QuickSort qs = new QuickSort();
        System.out.println("The Array");
        System.out.println(A);
        qs.quickSort(A, 0, (n - 1));
        System.out.println("The Array after QuickSort");
        System.out.println(A);
        System.out.println("");

    }
}

【问题讨论】:

  • 猜测,for 循环应该是for (int j = p ; j &lt; r - 1; j++) {
  • 也给出了超出范围的索引:(
  • 您能告诉我们A,以及pr 传递的值吗?
  • 当然,已将其添加到问题中。我将 p 作为开始( 0 ),将 r 作为结束 A.size - 1

标签: java arraylist indexoutofboundsexception quicksort


【解决方案1】:

问题是Collections.swap(A, A.get(i), A.get(j)); - 这将尝试使用A.get(i) 中的值作为列表中的索引,如果i 的值大于A.size(),显然会引发越界异常.

所以只用你想交换的位置替换它们:

Collections.swap(A, i, j);

Collections.swap(A, (i + 1), r);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多